I would like to return some data from c++ code as a numpy.array
object. I had a look at boost::python::numeric
, but its documentation is very terse. Can I get an example of e.g. returning a (not very large) vector<double>
to python? I don't mind doing copies of data.
|
|||||||
|
Another interface between Boost.Python and NumPy can be found here: https://github.com/ndarray/Boost.NumPy It's a moderately complete wrapper of the NumPy C-API into a Boost.Python interface, with the intention of eventually submitting it to Boost. I'm not sure the documentation is any better overall than boost::python::numeric at this point, but there are a lot of code examples and at least it's under active development. It's pretty low-level, and mostly focused on how to address the more difficult problem of how to pass C++ data to and from NumPy without copying, but here's how you'd do a copied std::vector return with that:
|
|||
|
Doing it using the numpy api directly is not necessarily difficult, but I use boost::multiarray regularly for my projects and find it convenient to transfer the shapes of the array between the C++/Python boundary automatically. So, here is my recipe. Use http://code.google.com/p/numpy-boost/, or better yet, this version of the numpy_boost.hpp header; which is a better fit for multi-file boost::python projects, although it uses some C++11. Then, from your boost::python code, use something like this:
|
|||||||
|
A solution that doesn't require you to download any special 3rd party C++ library (but you need numpy).
Of course you might write a function from double * and size, which is generic then invoke that from the vector by extracting this info. You could also write a template but you'd need some kind of mapping from data type to the |
||||
|