9
5

More than 3 years have passed since last update.

[Rust/Python] PyO3でnumpyを扱う (2020年8月版)

Posted at

Rust で実装した myfunction(x: f64) -> Array2<f64> を Python から呼ぶコード例です. ゼロコピーなので大きなデータを Rust 側で生成して Python で解析する場合におすすめです. 頻繁に使うのでコピペ用に.

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(())
}

コンパイルと実行例:

$ cargo build --release
$ ln -s ./target/release/libmypackage.so mypackage.so
$ 
$ python3
>>> import mypackage
>>> x = 3.14
>>> arr = mypackage.myfunction(x)
9
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
9
5