SWIG - Wring C string string to python list

I was wondering how to correctly transfer an array of strings in C to a Python list using SWIG.

The array is inside the structure:

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

SWIG automatically wraps some_string in a python string.

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

I 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 variable my_array appears as SwigPyObject: _20afba0100000000_p_p_char.

Interestingly, this is because char ** is inside the structure? Maybe I need to tell SWIG what?

Any ideas?

+4
source share
3 answers

I do not think that there is an opportunity to automatically process this conversion to SWIG. You need to use the Typemap function for SWIG and the recording type converter manually. Here you can find the conversion from the Python list to char ** http://www.swig.org/Doc1.3/Python.html#Python_nn59 to do half the job. Now you need to check the rest of the Typemap documentation and write the converter from char ** to the Python list.

+1
source

I'm sorry I'm a little off topic, but if this is an option for you, I highly recommend using ctypes instead of swig. Here's a related question that I asked earlier in the context of ctypes: Passing a list of strings from python / ctypes to a C function expecting char **

0
source

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 the structure .. look at the code generated by swig to confirm that the card was applied or not.

You may need to use something like:

 %typemap(python,out) struct Foo { 

To have a map that works on a Foo structure that returns.

Reference Information. I used the same type map definition that you used, but then for char ** successfully.

0
source

Source: https://habr.com/ru/post/1348185/


All Articles