0
0

PythonのコードをRustから使う

Last updated at Posted at 2024-06-12

概要

Rustを使ってロボット用ミドルウェアを作っています。Pythonも色々と便利なモジュールがあるので、RustからPythonで作ったモジュールを呼び出す機能を実装したのでメモを取ります。

Rustからはpyo3というクレートを使って呼び出すことにしました。

使用方法

環境

MacOS + rustc (1.77.2)

Cargo newする

$ cargo new pyo3_test

Cargo tomlを編集

pyo3 = {version = "*", features=["auto-initialize"]}

src/main.rsを編集

use pyo3::prelude::*; // 主要なモジュール

fn main() {
    // Python::with_gilでPython環境呼び出す
    let pyresult = Python::with_gil(|py| -> PyResult<Py<PyAny>> {
        // ここでコードをモジュールとしてロード。ロードした時にグローバルに置いたprintの行が実行される
        let module = PyModule::from_code_bound(py, 
            r#" 
print("Hello, World from Python!")

def function1():
    print("function1() called")
            "#
            , "", "")?;
        // ここでモジュールの中のfunction1にアクセスできるようになる
        let app_func: Py<PyAny> = module.getattr("function1")?.into();
        // 引数なしの関数として呼び出して返却値をそのまま返す。
        app_func.call0(py)        
    });
    println!("pyresult is {pyresult:?}");
}

cargo run

$ cargo run
Hello, World from Python!
function1() called
pyresult is Ok(Py(0x105d19d00))

これは超簡単な例だけど、基本の'き'です。

続き

0
0
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
0
0