From 64ba7df01c07f63ac4c476815656717b746d0cbc Mon Sep 17 00:00:00 2001 From: Adam Reichold Date: Mon, 3 Jan 2022 07:32:29 +0100 Subject: [PATCH] Make arrays backed by owned data writeable. --- CHANGELOG.md | 3 +++ src/array.rs | 12 ++++++------ tests/to_py.rs | 10 ++++++++++ 3 files changed, 19 insertions(+), 6 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index fe49ea1e5..c09b703c9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,8 @@ # Changelog +- Unreleased + - Make arrays produced via `IntoPyArray`, i.e. those owning Rust data, writeable ([#235](https://github.com/PyO3/rust-numpy/pull/235)) + - v0.15.0 - [Remove resolver from Cargo.toml](https://github.com/PyO3/rust-numpy/pull/202) - [Bump PyO3 to 0.15](https://github.com/PyO3/rust-numpy/pull/212) diff --git a/src/array.rs b/src/array.rs index 3565e01d0..578ee50e9 100644 --- a/src/array.rs +++ b/src/array.rs @@ -432,7 +432,7 @@ impl PyArray { ptr::null_mut(), // data 0, // itemsize flag, // flag - ptr::null_mut(), //obj + ptr::null_mut(), // obj ); Self::from_owned_ptr(py, ptr) } @@ -458,11 +458,11 @@ impl PyArray { dims.ndim_cint(), dims.as_dims_ptr(), T::npy_type() as i32, - strides as *mut _, // strides - data_ptr as _, // data - mem::size_of::() as i32, // itemsize - 0, // flag - ptr::null_mut(), //obj + strides as *mut _, // strides + data_ptr as _, // data + mem::size_of::() as i32, // itemsize + npyffi::NPY_ARRAY_WRITEABLE, // flag + ptr::null_mut(), // obj ); PY_ARRAY_API.PyArray_SetBaseObject(ptr as *mut npyffi::PyArrayObject, cell as _); Self::from_owned_ptr(py, ptr) diff --git a/tests/to_py.rs b/tests/to_py.rs index da08424bf..410260767 100644 --- a/tests/to_py.rs +++ b/tests/to_py.rs @@ -115,6 +115,16 @@ fn into_pyarray_cant_resize() { }) } +#[test] +fn into_pyarray_can_write() { + let a = vec![1, 2, 3]; + pyo3::Python::with_gil(|py| { + let arr = a.into_pyarray(py); + pyo3::py_run!(py, arr, "assert arr.flags['WRITEABLE']"); + pyo3::py_run!(py, arr, "arr[1] = 4"); + }) +} + /// Check that into_pyarray works for ndarray of which the pointer of the first element is /// not at the start. See https://github.com/PyO3/rust-numpy/issues/182 for more #[test]