Wednesday, 18 September 2013

Wrapping arrays in Boost Python

Wrapping arrays in Boost Python

I have a series of C++ structures I am trying to wrap using boost python.
I've run into difficulties when these structures contain arrays. I am
trying to do this with minimal overhead and unfortunately I can't make any
modifications to the structs themselves. So for instance say I have
struct Foo
{
int vals[3];
};
I would like to be able to access this in python as follows:
f = Foo()
f.vals[0] = 10
print f.vals[0]
Right now I am using a series of get/set functions which works but is very
inelegant and inconsistent with accessing the other non-array members.
Here is my current solution:
int getVals (Foo f, int index) { return f.vals[index]; }
void setVals (Foo& f, int index, int value) { f.vals[index] = value; }
boost::python::class_< Foo > ( "Foo", init<>() )
.def ( "getVals", &getVals )
.def ( "setVals", &setVals );
I am fine with having the get/set functions (as there are certain cases
where I need to implement a custom get or set operation) but I am not sure
how to incorporate the [] operator to access the elements of the array. In
other classes which themselves are accessible with the [] operator I have
been able to use _getitem_ and _setitem_ which have worked perfectly, but
I'm not sure how I would do this with class members if that would even be
possible.

No comments:

Post a Comment