nb::nnarray and []-operator? #1417
|
Hi. I'm currently porting my project from pybind11 to nanobind and I'm trying to keep API for existing python code. Here, -- WBR, Timofey C. |
Replies: 3 comments 2 replies
|
So what's wrong with the snippet? Maybe I am just confused, but that should work, no? |
|
ah, you are saying that self.buffer_h doesn't override the |
|
The copy isn't coming from your design, it's the default policy of template <typename T> object cast(T &&value, rv_policy policy = rv_policy::automatic_reference)and What you want is the Python object that already exists for that instance, and .def_prop_ro("view",
[](vcache_holder &self) { return self.buffer_h; },
nb::rv_policy::reference_internal)
.def("__getitem__", [](vcache_holder &self, nb::handle index) {
return nb::find(self).attr("view").attr("__getitem__")(index);
})
.def("__setitem__", [](vcache_holder &self, nb::handle index, nb::handle value) {
nb::find(self).attr("view").attr("__setitem__")(index, value);
})
Keep .def("view",
[](Matrix4f &m){ return Array(m.data); },
nb::rv_policy::reference_internal);Without it the NumPy array points into storage that the C++ object may have already freed. One note on cost: every |
The copy isn't coming from your design, it's the default policy of
nb::cast. Its signature isand
automatic_referencebehaves likeautomaticexcept for pointers, whereautomaticis documented as falling back to "take_ownershipwhen the return value is a pointer,movewhen it is a rvalue reference, andcopywhen it is a lvalue reference". You pass an lvalue reference, so you getcopy, hence the call to a copy constructor you don't have.What you want is the Python object that already exists for that instance, and
nb::findreturns exactly that without creating anything:.def_prop_ro("view", …