ユーザ用ツール

サイト用ツール


youtube:python-mixing-007

RustとPythonの様子見

作成日: 2023-08-12 (土)

第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<PyNone> {
    greet(name);
    Ok(PyNone)
}

fn add(_py: Python, a: i32, b: i32) -> PyResult<i32> {
    let out = a + b;
    Ok(out)
}

youtube/python-mixing-007.txt · 最終更新: 2024/07/12 02:51 by freemikan

特に明示されていない限り、本Wikiの内容は次のライセンスに従います: CC0 1.0 Universal
CC0 1.0 Universal Donate Powered by PHP Valid HTML5 Valid CSS Driven by DokuWiki