I am building a simple python extension to process numpy.ndarray objects using rust-numpy crate. I want to save numpy.ndarray objects in static or thread local variables for later process:
use std::cell::RefCell;
use numpy::PyReadwriteArray1;
use pyo3::{Bound, pymodule, PyResult, types::PyModule};
thread_local! {
static ARRAYS: RefCell<Vec::<PyReadwriteArray1<i32>>> = RefCell::new(Vec::<PyReadwriteArray1<i32>>::new());
}
#[pymodule]
fn rust_ext<'py>(m: &Bound<'py, PyModule>) -> PyResult<()> {
#[pyfn(m)]
fn register_array(mut x: PyReadwriteArray1<i32>) {
x.as_array_mut()[0] = 100;
ARRAYS.with_borrow_mut(|v| v.push(x));
}
Ok(())
}
But I got lifetime compile error:
static ARRAYS: RefCell<Vec::<PyReadwriteArray1<i32>>> = RefCell::new(Vec::<PyReadwriteArray1<i32>>::new());
| ^ expected named lifetime parameter
So is it possible to save python objects in extension written in Rust? If so, how to fix ‘py lifetime issue?