-
Notifications
You must be signed in to change notification settings - Fork 2.1k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Construct py::array without copy #323
Comments
To make it truly safe (reference counting and all), you also need to inform PyArray about the object which owns the buffer. A way of directly doing this sort of stuff with pybind11 is in the works (#308) but may still take a bit. |
Ok guys, after reading lots of SO articles, lots of pybind issues, PRs and discussions and after reading the code I figured it out: HUH! 😄 Now my code looks like this: void addInput(std::shared_ptr<const MyFancyMatrix> packet)
{
// When a valid object is passed as 'base', it tells pybind not to take ownership of the data,
// because 'base' will own it. In fact 'packet' will own it, but - psss! - , we don't tell it to
// pybind... Alos note that ANY valid object is good for this purpose, so I chose "str"...
py::str dummyDataOwner;
py::array input{getNumpyDTypeFromElementType(packet->elementType()), packet->shape(),
packet->strides(), packet->data(), dummyDataOwner};
assert(!input.owndata()); // if fires, s.g. is not OK with ownership (probably matrix data was copied)
// ...
}
Awesome hacky undocumented stuff... 😁 🌟 |
it will be great if pybind11 could provide more documents on handling numpy arrays |
@LeslieGerman your approach worked perfectly - @power1628 I agree, documentation on this, even in the form of tests would be more reassuring as at least it's confirmed that this is a reasonable approach. |
Wouldn't using py::none() instead of dummyDataOwner be more ideal? The base property of input would still point at dummyDataOwner, or am I mistaken? |
Hi Wenzel,
I'm trying to construct a
py::array
from a bare pointer without copying data.In #27 you mentioned that
Could you please elaborate a bit on how to do this?
Also, it seems to me a simple alternative would be to optionally skip the
PyArray_NewCopy
call in the py::array constructor, something likeI tried this and it seems to work just fine. Am I missing something here?
Thanks!
The text was updated successfully, but these errors were encountered: