pybind / pybind11

Seamless operability between C++11 and Python
https://pybind11.readthedocs.io/
Other
15.1k stars 2.05k forks source link

[BUG]: pybind11 return numpy array by copy instead of reference. #4946

Open triple-Mu opened 7 months ago

triple-Mu commented 7 months ago

Required prerequisites

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
hesic73 commented 6 months ago

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))