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
source share