Accessing a C struct array to Python using SWIG

I am trying to call existing C code from Python. C code defines a structure B that contains an array struct A s. C code also defines a function that inserts values ​​into the structure when called. I can access the variable of an array element, but this is not a list (or something that supports indexing). Instead, I get an object that is a proxy for B* .

I found this question , but it does not look like it was fully resolved. I'm also not sure how to instantiate a Python B class to replace PyString_FromString() .

Below is the code needed to demonstrate my problem and its implementation:

example.h

 typedef struct A_s { unsigned int thing; unsigned int other; } A_t; typedef struct B_s { unsigned int size; A_t items[16]; } B_t; unsigned int foo(B_t* b); 

example.c

 #include "example.h" unsigned int foo(B_t* b) { b->size = 1; b->items[0].thing = 1; b->items[0].other = 2; } 

example.i

 %module example %{ #define SWIG_FILE_WITH_INIT #include "example.h" %} %include "example.h" 

setup.py

 from distutils.core import setup, Extension module1 = Extension('example', sources=['example.c', 'example.i']) setup(name='Example', version='0.1', ext_modules=[module1]) 

script.py - This uses the library and demonstrates a failure.

 import example b = example.B_t() example.foo(b) print b.size print b.items for i in xrange(b.size): print b.items[i] 

How to run everything:

 python setup.py build_ext --inplace mv example.so _example.so python script.py 
+4
source share
1 answer

you could write some helper functions of C, for example:

 int get_thing(B_t *this_b_t, int idx); int get_other(B_t *this_b_t, int idx); void set_thing(B_t *this_b_t, int idx, int val); void set_other(B_t *this_b_t, int idx, int val); 

wrap them, and then you can use the pointer that you get from example.B_t() to access the values ​​inside your data structure structure, for example.

 >>> b = example.B_t() >>> a_thing = example.get_thing(b, 0) >>> example.set_thing(b,0,999) 

Hope this is obvious that the implementation of these C functions should be - if I could not give an example ...

provided it is not as simple as the ability to access C arrays in the form of python lists - you can use typemaps to achieve this, but I cannot remember the exact syntax you will need in this case - you would need to do a bit of RTFM in the SWIG documentation

can also be duplicated here: accessing an array of nested structure in python using SWIG

0
source

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


All Articles