You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Simple example for exchanging ndarrays between Python and C++ extension #6
I've been searching for a simple example that shows how to exchange NumPy arrays between Python and an extension module written in C++ w/ Boost Python.
Let's make it a bit more concrete. How would you do the following:
Create a NumPy array in Python
Import extension module written in C++ with Boost Python and pass the array to a function in the module
The function does some simple operation on the array -- say square each element -- and returns the modified array, perhaps with a different size, to Python.
Also, if my C++ mostly needs data as vector< vector< double > >or double **, would using the ndarray interface in the C-code incur a lot of performance overhead?
You might want to check out libs/examples/gaussian.cpp, which does a little more than this (it uses Boost.NumPy to create converters for a custom matrix/vector type), but still has a lot of the same code.
I'll get to work adding another, simpler example. In the meantime, to answer your question about overhead:
If you use the ndarray interface to extract the data pointer, shape, and strides, and then increment those yourself, there's essentially no overhead at all relative to using the NumPy C-API. If you use it to index each element, the overhead is essentially one non-inlined function call per access.
Using vector< vector< double > > is going to require copying all the data in the area no matter what interface you use.
Activity
TallJimbo commentedon May 12, 2012
You might want to check out
libs/examples/gaussian.cpp, which does a little more than this (it uses Boost.NumPy to create converters for a custom matrix/vector type), but still has a lot of the same code.I'll get to work adding another, simpler example. In the meantime, to answer your question about overhead:
vector< vector< double > >is going to require copying all the data in the area no matter what interface you use.Add example (wrap.py) to demonstrate how to wrap simple functions tha…
TallJimbo commentedon May 13, 2012
Please check out libs/numpy/example.cpp to see if it matches what you're looking for.
Kameshkk commentedon May 14, 2012
Excellent! Thanks a bunch!