This is a code example that calls myfunction (x: f64)-> Array2 <f64>
implemented in Rust from Python. Since it is a zero copy, it is recommended when large data is generated on the Rust side and analyzed by Python. Frequently used So for copy and paste.
Cargo.toml
[lib]
name = "mypackage"
crate-type = ["cdylib"]
[dependencies]
pyo3 = { version = "0.11", features = ["extension-module"] }
ndarray = "0.13"
numpy = "0.11"
src/lib.rs
use pyo3::prelude::*;
use ndarray::Array2;
use numpy::{IntoPyArray, PyArray2};
#[pymodule]
fn mypackage(_py: Python, m: &PyModule) -> PyResult<()> {
#[pyfn(m, "myfunction")]
fn myfunction_py<'py>(py: Python<'py>, x: f64) -> &'py PyArray2<f64> {
let arr = myfunction(x);
arr.into_pyarray(py)
}
Ok(())
}
Compile and run example:
$ cargo build --release
$ ln -s ./target/release/libmypackage.so mypackage.so
$
$ python3
>>> import mypackage
>>> x = 3.14
>>> arr = mypackage.myfunction(x)
Recommended Posts