pybind11
pybind11 copied to clipboard
[BUG]: pybind11 return numpy array by copy instead of reference.
Required prerequisites
- [X] Make sure you've read the documentation. Your issue may be addressed there.
- [X] Search the issue tracker and Discussions to verify that this hasn't already been reported. +1 or comment there if it has.
- [X] Consider asking first in the Gitter chat room or in a Discussion.
What version (or hash if on master) of pybind11 are you using?
2.11
Problem description
py::array_t<float> return_from_cpp()
{
float* data = new float[5];
printf("data ptr: %ld", data);
return py::array_t<float>({1, 5}, data);
}
I want to return an existing data in c++ to python, so I try build a py::array_t<float> object by pointer.
But python receive a copy array.
So what should I do?
Reproducible example code
c++
py::array_t<float> return_from_cpp()
{
float* data = new float[5];
printf("data ptr: %ld", data);
return py::array_t<float>({1, 5}, data);
}
from package import return_from_cpp
data = return_from_cpp()
print(data.ctypes.data)
### Is this a regression? Put the last known working version here if it is.
Not a regression
According to https://pybind11.readthedocs.io/en/stable/advanced/pycpp/numpy.html#memory-view, maybe we can use memoryview to avoid copy:
py::memoryview return_from_cpp()
{
float* data = new float[5];
printf("%lld\n", data);
return py::memoryview::from_buffer(data,{1, 5},{sizeof(float) * 5, sizeof(float)});
}
from package import return_from_cpp
import numpy as np
view = return_from_cpp()
data = np.asarray(view)
print(id(data.ctypes.data))