0
0

PythonのコードをRustから使う その3 引数を与える

Last updated at Posted at 2024-06-12

前回の記事

概要

前回の記事で、関数の返り値を受け取る基本をやったので、今度は引数を与えてみる

src/main.rs

use pyo3::{prelude::*, types::PyTuple}; // 主要なモジュール

fn main() {
    let mut rust_value: i64 = 0; // 結果を受け取るための変数
    
    let arg0 = 1;
    let arg1 = 2;

    // 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(arg0, arg1):
    print("function1() called. add two args.")
    return arg0 + arg1
            "#
            , "", "")?;
        // ここでモジュールの中のfunction1にアクセスできるようになる
        let app_func: Py<PyAny> = module.getattr("function1")?.into();
        // 引数をPyTupleでまとめて呼び出し。返却値を受け取る。
        let func_result = app_func.call1(py, PyTuple::new_bound(py, [arg0, arg1]))?;

        rust_value = func_result.clone().extract(py)?; // 結果をi64に変換する
        Ok(func_result)
    });
    println!("pyresult is {pyresult:?}");
    println!("rust_value is {rust_value:?}");
}

cargo run

$ cargo run
Hello, World from Python!
function1() called. add two args.
pyresult is Ok(Py(0x104fa51f8))
rust_value is 3

PyTupleでまとめて渡すのがポイント

次の記事

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