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
It's a bit late, but after many unsuccessful tries I found a way to expose c++ arrays as numpy arrays directly. Here is a short C++11 example using boost::python and Eigen:
#include
#include
#include
// c++ type
struct my_type {
Eigen::Vector3d position;
};
// wrap c++ array as numpy array
static boost::python::object wrap(double* data, npy_intp size) {
using namespace boost::python;
npy_intp shape[1] = { size }; // array size
PyObject* obj = PyArray_New(&PyArray_Type, 1, shape, NPY_DOUBLE, // data type
NULL, data, // data pointer
0, NPY_ARRAY_CARRAY, // NPY_ARRAY_CARRAY_RO for readonly
NULL);
handle<> array( obj );
return object(array);
}
// module definition
BOOST_PYTHON_MODULE(test)
{
// numpy requires this
import_array();
using namespace boost::python;
// wrapper for my_type
class_< my_type >("my_type")
.add_property("position", +[](my_type& self) -> object {
return wrap(self.position.data(), self.position.size());
});
}
The example describes a "getter" for the property. For the "setter", the easiest way is to assign the array elements manually from a boost::python::object using a boost::python::stl_input_iterator.