Skip to content

Instantly share code, notes, and snippets.

@masakielastic
Last active November 29, 2025 03:36
Show Gist options
  • Select an option

  • Save masakielastic/73d5452ffe37e17f6984d88b36db0f1e to your computer and use it in GitHub Desktop.

Select an option

Save masakielastic/73d5452ffe37e17f6984d88b36db0f1e to your computer and use it in GitHub Desktop.
PyO3 + maturin による Python モジュールの作成

PyO3 + maturin による Python モジュールの作成

2025年12月時点で PyO3 が Python 3.14 を正式サポートしていないので Python 3.13 を利用しました。

プロジェクトのセットアップ

cargo new --lib my_rust_py
cd my_rust_py
[package]
name = "my_rust_py"
version = "0.1.0"
edition = "2021"

[lib]
name = "my_rust_py"
crate-type = ["cdylib"]

[dependencies]
pyo3 = { version = "0.22", features = ["extension-module"] }

Python 環境をアクティベートします。

uv venv .venv
source .venv/bin/activate
pip install maturin

Rust のコード

use pyo3::prelude::*;

/// 普通の Rust 関数
fn rust_add(a: i64, b: i64) -> i64 {
    a + b
}

/// Python から呼び出せる関数
#[pyfunction]
fn add(a: i64, b: i64) -> PyResult<i64> {
    Ok(rust_add(a, b))
}

/// Python モジュールの定義
#[pymodule]
fn my_rust_py(m: &Bound<'_, PyModule>) -> PyResult<()> {
    // 関数をモジュールに登録
    m.add_function(wrap_pyfunction!(add, m)?)?;
    Ok(())
}

Python 環境の導入

uv venv .venv
source .venv/bin/activate
pip install maturin

ビルドして Python から使う

プロジェクトのルートで次のコマンドを実行すれば「現在アクティブな Python 環境」に my_rust_py がインストールされる

maturin develop

REPL で確認する。

>>> import my_rust_py
>>> my_rust_py.add(3, 5)
8

wheel を作成する

次のコマンドで target/wheels/ に wheel が作成されます。

maturin build --release

次のコマンドでインストールされます。

pip install target/wheels/my_rust_py-0.1.0-...whl
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment