how to return numpy.array from boost::python?

后端 未结 5 2134
有刺的猬
有刺的猬 2020-11-28 08:03

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

5条回答
  •  心在旅途
    2020-11-28 08:46

    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:

    PyObject* myfunc(/*....*/)
    {
       // If your data is already in a boost::multiarray object:
       // numpy_boost< double, 1 > to_python( numpy_from_boost_array(result_cm) );
       // otherwise:
       numpy_boost< double, 1> to_python( boost::extents[n] );
       std::copy( my_vector.begin(), my_vector.end(), to_python.begin() );
    
       PyObject* result = to_python.py_ptr();
       Py_INCREF( result );
    
       return result;
    }
    

提交回复
热议问题