Boost.Python create extra functions not in wrapped object

Stou Sandalski stou.sandalski at gmail.com
Thu Apr 19 03:37:36 EDT 2007


Hi,

I have a python library created by wrapping the C++ library using
Boost.Python, the problem is that the wrappers are not very
pythonic.... so I want to add some methods that do not exist in the C+
+ implementation, that would create a better Python interface.

For example to initialize the data in an object in the library one
must iterate through every point, setting a value for each
individually.  That's the way it works in C++ but in python it would
be nice to instead just have one call that can receive a numpy array
or a tuple. I want to add a call like: setData(array) to the python
object, a call that does not exist in the C++ implementation and then
in the C++ wrappers actually use setData to iterate through the array
and set the values using the normal C++ method, say setValue(index,
value).

Something along the lines of this (initData is not in the constructor
on purpose) C++ object:

class Foo
{
public:
     void initData(int size)
     {
        data = new float[size];
     }; // Create the data array
     void setValue(int index, float value) // Set given value
     {
         data[index] = value;
     }
private:
     float *data;
};


In python however I want to do this:

obj = foo()
ar = array([1,2,3,4,5], dtype=float)

foo.setData(ar)

Or even better:

ar = array([1,2,3,4,5], dtype=float)
obj = foo(ar)

And have it somehow call initData() and setValue() iteration inside
the C++ code of the wrapper.  I've only used SWIG and don't really
know much about Boost, I am not even sure how to label what I am
trying to do.

Can this be done with Boost, without changing the C++ library?

Regards,

Stou




More information about the Python-list mailing list