Passing a numpy FROM C ++ array using boost python

I need to pass a numpy array to a python function from C ++. The code is below. Python side:

import numpy as np import convert as cv def f(x): x[0] = 5. return len(x) if __name__ == '__main__': y = np.array([1., 2., 3., 4.]) x = cv.func_n(f, y) print x 

C ++ side:

 #include <iostream> #include <boost/python.hpp> using namespace boost::python; double func_n(PyObject* f, numeric::array &x) { std::cerr << "Inside func_n\n"; return boost::python::call<double>(f, boost::ref(x)); } BOOST_PYTHON_MODULE(convert) { numeric::array::set_module_and_type("numpy", "ndarray"); def("func_n", &func_n); } 

C ++ code is supposed to make python functopn and a numpy array as two arguments, and then pass the numpy array to the python function. The error I am getting is:

 Traceback (most recent call last): File "mm.py", line 11, in <module> x = cv.func_n(f, y) TypeError: No Python class registered for C++ class class boost::python::numeric::array 

Why? Should I register a module during a recursive invocation of the interpreter, and if so, how?

+4
source share
1 answer

boost::ref(x) returns boost::reference_wrapper<T> , which allows you to pass function references by value.

boost :: python :: call docs show that arguments are processed differently depending on their type. If arg is boost::reference_wrapper<T> , it effectively passes the x reference to Python.

So, in the code above, you passed a reference to your numeric :: array in Python. The function you call from Python also accepts the link.

Now I'm not sure about this, but I suspect that since you never passed a numeric :: array between Python / C ++, boost :: python decided not to wrap it or create converters (since you're really just bypassing the addresses). Perhaps that is why you did not notice the class of the Python class for the type numeric :: array.

0
source

Source: https://habr.com/ru/post/1441325/


All Articles