maturin というのを使うと、 Rustで、Python の拡張モジュールを書くのが簡単になってた。
基本は、ここらへんの手順に従う
- https://www.maturin.rs/tutorial.html#install-and-configure-maturin-in-a-virtual-environment
- https://gihyo.jp/article/2023/07/monthly-python-2307
foo パッケージに、 Rust の拡張モジュールを calc を定義して、python のコードから呼び出してみる。
::
mkdir work
cd work
python3 -m venv venv
. venv/bin/activate
pip install -U pip maturin
maturin init foo # (pyo3 を選ぶ)
cd foo
mkdir foo
pyproject.toml の `[tool.maturin]` に、
::
module-name = "foo.calc"
を追加
src/lib.rs の `#[pymodule]` のモジュール名を calc に変更
この状態で、モジュール calc に、数値を2つ受け取って加算した結果を文字列で返す sum_as_string() という関数が定義されている。
インプレースでビルドして
::
pip install -e .
Interactivae shell で、動作確認
::
>>> from foo import calc
>>> calc.sum_as_string(1, 2)
'3'
>>>
::
maturin build
を実行すると、 target/wheels に wheel ができる
この記事へのコメント