1

I use swig wrapped some c++ api function. There is one function, the interface is f(char*[] strs).

How can I pass a valid parameter to this function. This is what I did.

str = ["str","str2"]
f(str)

it will throw error

TypeError: in method 'f', argument 1 of type 'char *[]  
2
  • 1
    check your f function, it takes the char [] list and you given list of string. So call f function with char list. Commented Jul 2, 2014 at 6:12
  • @Odedra char* is a string in C. you can init a char* [] like this. char *list[] = {"str","str1"} Commented Jul 2, 2014 at 17:34

1 Answer 1

1

SWIG does not convert arrays to Python lists automatically. Since you are using C++, use std::string and std::vector for your f, then SWIG will make all the necessary conversions automatically (don't forget to include "std_vector.i" and such, see the SWIG docs):

void f(std::vector<std::string> > strs)

If you cannot modify the declaration of f, you can create an %inline wrapper in the .i:

%inline {
    void f(const std::vector<std::string> >& strs) 
    {
        // create tmpCharArray of type char*[] from strs
        const char* tmpCharArray[] = new const char* [strs.size()];
        for (i=0; i<strs.size(); i++) 
              tmpCharArray[i] = strs[i].c_str();
        f(tmpCharArray);
        delete[] tmpCharArray;
     }
}
Sign up to request clarification or add additional context in comments.

3 Comments

Cool. Let me know if there is any improvement needed for you to upvote, and welcome to SO!
It is a good enough answer. I find something cooler. this way, I do not even have to write a wrapper, and char** can be used for all the functions which required.
Thanks for posting the link.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.