问题
I attempting to call into existing C code from Python. The C code defines a struct B
that contains an struct array of A
s. The C code also defines a function that puts values into the structure when called. I can access the array member variable, but it is not an list (or something that supports indexing). Instead, I am getting an object that is a proxy for B*
.
I found this question, but it doesn't look like it was completely resolved. I'm also not sure how to make an instance of the Python class B
to replace the PyString_FromString()
.
Below is the code needed to demonstrate my issue and how to execute it:
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 library and demonstrates the 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
回答1:
you could write some C helper functions like:
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 these and you can then use the pointer that you get from example.B_t()
to access values from within your data-structure arrangement, e.g.
>>> b = example.B_t()
>>> a_thing = example.get_thing(b, 0)
>>> example.set_thing(b,0,999)
Hopefully its obvious what the implementation of these C functions should be - if not I could provide an example...
granted this isn't as seamless as being able to access C arrays as python lists - you might be able to use typemaps to achieve this but I can't remember the exact syntax you would need in this instance - you'd have to do a bit of RTFM on the SWIG documentation
also possible duplicate here: nested structure array access in python using SWIG
来源:https://stackoverflow.com/questions/12829198/accessing-c-struct-array-to-python-with-swig