Skip to content

Commit 0fa3bd1

Browse files
committed
Add document about PyArray::to_owned
1 parent cd82299 commit 0fa3bd1

File tree

1 file changed

+22
-0
lines changed

1 file changed

+22
-0
lines changed

src/array.rs

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -62,6 +62,28 @@ impl<T> PyArray<T> {
6262
self.as_ptr() as _
6363
}
6464

65+
/// Get `PyArray` from `&PyArray`, by increasing ref counts.
66+
///
67+
/// You can use this method when you have to avoid lifetime annotation to your function args
68+
/// or return types, like used with pyo3's `pymethod`.
69+
///
70+
/// Since this method increases refcount, you can use `PyArray` even after `pyo3::GILGuard`
71+
/// dropped, in most cases.
72+
///
73+
/// # Example
74+
/// ```
75+
/// # extern crate pyo3; extern crate numpy; fn main() {
76+
/// use pyo3::{GILGuard, Python};
77+
/// use numpy::PyArray;
78+
/// fn return_py_array() -> PyArray<i32> {
79+
/// let gil = Python::acquire_gil();
80+
/// let array = PyArray::zeros(gil.python(), &[5], false);
81+
/// array.to_owned(gil.python())
82+
/// }
83+
/// let array = return_py_array();
84+
/// assert_eq!(array.as_slice().unwrap(), &[0, 0, 0, 0, 0]);
85+
/// # }
86+
/// ```
6587
pub fn to_owned(&self, py: Python) -> Self {
6688
let obj = unsafe { PyObject::from_borrowed_ptr(py, self.as_ptr()) };
6789
PyArray(obj, PhantomData)

0 commit comments

Comments
 (0)