[Feature Usage] #5848
yashgupta1299
started this conversation in
General
[Feature Usage]
#5848
Replies: 0 comments
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
-
This is a correct way to use it? Because when I am not using keep alive policy it is stil working? why. Also In existing usage should I take buffer as const ref or it is fine??
I want to make sure data_view remain valid and even if arr goes out of scope or del still data_view points to valid memory. I do not want to do a memcopy from python to pybind11 rather want to use the same mem inside c++ via pybind 11.
Python Code:
arr = np.array([1, 2, 3, 4, 5], dtype=np.uint8)
data = Data(arr)
data_view = np.frombuffer(data, dtype=np.uint8)
arr[0] = 7
data_view[1] = 8
print(arr, data_view) # [7 8 3 4 5] [7 8 3 4 5]
typedef struct {
// Buffer Size
size_t size;
// Buffer pointer
uint8_t *data;
} Data;
PYBIND11_MODULE(mymod, m) {
py::class<Data, std::shared_ptr>(m, "Data", py::buffer_protocol())
.def(py::init<>())
.def(py::init([](py::buffer buffer) {
py::buffer_info info = buffer.request();
auto qdata = std::make_shared();
qdata->size = info.itemsize * info.size;
qdata->data = static_cast<uint8_t*>(info.ptr);
return qdata;
}), py::keep_alive<1, 2>())
.def_buffer([](Data &qdata) -> py::buffer_info {
return pybind11::buffer_info(qdata.data, qdata.size);
})
.def_readonly("size", &Data::size)
.def_readonly("data", &Data::data);
}
Beta Was this translation helpful? Give feedback.
All reactions