文書の過去の版を表示しています。
RustとPythonの様子見
作成日: 2023-08-12 (土)
プロジェクトレイアウト
. └── example/ ├── Cargo.toml └── src/ └── lib.rs
example
rust-cpythonを使ったPythonの拡張モジュール。
Cargo.toml
<codeprism title=Cargo.toml lang=toml el=true> [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”] </codeprism>
src/lib.rs
<codeprism title=src/lib.rs lang=rust el=true> 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<PyNone> {
greet(name); Ok(PyNone)
}
fn add(_py: Python, a: i32, b: i32) → PyResult<i32> {
let out = a + b; Ok(out)
} </codeprism>