====== RustとPythonの様子見 ====== 作成日: 2023-08-12 (土) [[https://youtu.be/5A9lpLZy_rQ|第7回 RustとPythonの様子見]] プロジェクトレイアウト . └── example/ ├── Cargo.toml └── src/ └── lib.rs ===== example ===== rust-cpythonを使ったPythonの拡張モジュール。 ==== Cargo.toml ==== [package] name = "foo" version = "0.1.0" edition = "2021" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html [dependencies] [lib] name = "foo" crate-type = ["cdylib"] [dependencies.cpython] version = "0.7" features = ["extension-module"] ==== src/lib.rs ==== extern crate cpython; use cpython::{py_fn, py_module_initializer, PyNone, PyResult, Python}; py_module_initializer!(foo, |py, m| { m.add(py, "__doc__", "A module written in Rust.")?; m.add(py, "greet", py_fn!(py, greet_py(name: &str)))?; m.add(py, "add", py_fn!(py, add(a: i32, b: i32)))?; Ok(()) }); fn greet(name: &str) { println!("Hello, {}!", name); } fn greet_py(_py: Python, name: &str) -> PyResult { greet(name); Ok(PyNone) } fn add(_py: Python, a: i32, b: i32) -> PyResult { let out = a + b; Ok(out) }