SWIG - Wrap C string array to python list

混江龙づ霸主 提交于 2019-12-08 21:55:59

问题


I was wondering what is the correct way to wrap an array of strings in C to a Python list using SWIG.

The array is inside a struct :

typedef struct {
   char** my_array;
   char* some_string; 
}Foo;

SWIG automatically wraps some_string to a python string.

What should I put in the SWIG interface file so that I can access my_array in Python as a regular Python string list ['string1', 'string2' ] ?

I have used typemap as sugested :

%typemap(python,out) char** {
  int len,i;
  len = 0;
  while ($1[len]) len++;
  $result = PyList_New(len);
  for (i = 0; i < len; i++) {
    PyList_SetItem($result,i,PyString_FromString($1[i]));
  }
}

But that still didn't work. In Python, the my_array variable appears as SwigPyObject: _20afba0100000000_p_p_char.

I wonder if that is because the char** is inside a struct? Maybe I need to inform SWIG that?

Any ideas?


回答1:


I don't think there is a option to handle this conversion automatically in SWIG. You need use Typemap feature of SWIG and write type converter manually. Here you can find a conversion from Python list to char** http://www.swig.org/Doc1.3/Python.html#Python_nn59 so half of job is done. What you need to do right now is to check rest of documentation of Typemap and write converter from char** to Python list.




回答2:


I am not an expert on this but I think:

%typemap(python,out) char** {

applies to a function that returns char **. Your char ** is inside a structure.. have a look at the code generated by swig to confirm the map got applied or not.

You might have to use something like:

%typemap(python,out) struct Foo {

To have a map that works on a structure Foo that gets returned.

Background: I used the same typemap definition as you used, but then for a char ** successfully.




回答3:


I am sorry for being slightly off-topic, but if it is an option for you I would strongly recommend using ctypes instead of swig. Here is a related question I asked previously in ctypes context: Passing a list of strings to from python/ctypes to C function expecting char **



来源:https://stackoverflow.com/questions/5670456/swig-wrap-c-string-array-to-python-list

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!