Skip to content
Advertisement

pybind11 modify numpy array from C++

EDIT: It works now, I do not know why. Don’t think I changed anything

I want to pass in and modify a large numpy array with pybind11. Because it’s large I want to avoid copying it and returning a new one.

Here’s the code:

JavaScript

I think the py::array::forcecast is causing a conversion and so leaving the input matrix unmodified (in python). When I remove that though I get a runtime error, when I remove ::c_style it runs but again in python the numpy array is the same.

Basically my question is how can one pass and modify a numpy array with pybind11?

Advertisement

Answer

I just had the same problem. If, from Python, you pass a numpy array of the type matching the C++ argument then no conversion happens, and you can modify the data in-place i.e. for py::array_t<float> argument pass in a numpy np.float32 array. If you happen to pass in a np.float64 array (the default type) then pybind11 does the conversion due to the py::array::forcecast template parameter (default on py::array_t<T>), so your C++ function only gets a converted copy of a numpy array, and any changes are lost after returning.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement