Avoiding copies of arrays from python to rust #432
-
Hello, If I am not mistaken, it is possible to convert a Rust-allocated array into a NumPy array without copying the data: https://docs.rs/numpy/latest/numpy/convert/trait.IntoPyArray.html However, I do not think that there's a way to go the other way around and obtain a Rust reference to the data of a NumPy array that is valid not only while the GIL is acquired by Rust code, but that is valid permanently (i.e. for the lifetime of the Python interpreter). I believe that this is the case because there is no way to make sure that Rust's aliasing rules are enforced on the Python side. After all, as far as I know there is no way to make a NumPy array truly immutable. But what if there was a Python array type that was truly immutable. Wouldn't it then be safe to obtain and hold multiple Rust references (even from different threads) to such an array? After all if these references from Rust are accounted for by Python's GC, they won't be destroyed. And since they are immutable, there's no way to modify them on the Python side as well. (I am the author of the small numpy-like Python package tinyarray that happens to implement immutable NumPy-like arrays for CPython.) |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 7 replies
-
You can make your own pyclasses that do this. See https://docs.rs/pyo3/latest/pyo3/prelude/struct.Py.html#method.get PyString and PyBytes also have a similar method. |
Beta Was this translation helpful? Give feedback.
-
After reading through most of the discussions related to #274 (motivated by #433), I wonder: Right now it doesn't seem to be possible to obtain a (mutable or read-only) view of a NumPy array that is valid not only while the GIL is held by Rust code. But isn't the safety simulation exactly the same as the one described in https://docs.rs/numpy/0.21.0/numpy/borrow/index.html, i.e. that If this is true, shouldn't there be a way to obtain a view that lives beyond GIL acquisition? |
Beta Was this translation helpful? Give feedback.
You can make your own pyclasses that do this. See https://docs.rs/pyo3/latest/pyo3/prelude/struct.Py.html#method.get
PyString and PyBytes also have a similar method.