Rust 与 Python 在 Linux 上的集成方法
方法总览与选型
方法一 Python 调用 Rust 扩展模块(PyO3 + Maturin)
maturin new myrustlib && cd myrustlibcargo new myrustlib --lib,在 Cargo.toml 添加
[lib] crate-type = ["cdylib"]pyo3 = { version = "0.20", features = ["extension-module"] }src/lib.rs
use pyo3::prelude::*;#[pyfunction] fn add(a: i32, b: i32) -> PyResult<i32> { Ok(a + b) }#[pymodule] fn myrustlib(_py: Python, m: &PyModule) -> PyResult<()> { m.add_function(wrap_pyfunction!(add, m)?)?; Ok(()) }maturin develop(在 Python 环境中即时可用)maturin build 生成 wheel,随后 pip install dist/*.whlimport myrustlib; print(myrustlib.add(3, 4))方法二 Rust 调用 Python(嵌入解释器)
pyo3 依赖,Rust 侧通过 Python::acquire_gil 获取 GIL,然后执行 Python 代码或调用对象。use pyo3::prelude::*; use pyo3::types::PyString;let gil = Python::acquire_gil(); let py = gil.python();py.run(r#"def greet(name): return f"Hello, {name}!""#, None, None)?;let greet = py.eval("greet", None, None)?;let res: String = greet.call1((PyString::new(py, "Rust"),))?.extract()?;println!("{}", res);方法三 C ABI / FFI 通用桥接(cdylib + ctypes/ cffi)
Cargo.toml 设置 [lib] crate-type = ["cdylib"];导出 extern "C" 函数,必要时用 #[no_mangle]。#[no_mangle] pub extern "C" fn add(a: i32, b: i32) -> i32 { a + b }cargo build --release,产物为 libxxx.so。import ctypes; lib = ctypes.CDLL("./target/release/libxxx.so")lib.add.argtypes = (ctypes.c_int, ctypes.c_int); lib.add.restype = ctypes.c_intprint(lib.add(3, 4))方法四 进程与服务化调用(子进程 / HTTP / gRPC)
std::process::Command 调用 python script.py 并解析 stdout/stderr;简单可靠、隔离性好。实践要点与常见问题
Python::allow_threads),或将计算放到 Rayon/线程池后回到 Python 前重新获取 GIL。rustup target add x86_64-unknown-linux-musl && cargo build --release --target x86_64-unknown-linux-musl。develop/build/publish 流程,简化本地开发与发布到 PyPI 的步骤。maturin develop 快速迭代;必要时在 Rust 侧用 println! 或日志,在 Python 侧用 pytest/unittest 做回归。