参考文档:https://github.com/PyO3/pyo3
创建python虚拟环境:
conda create --name pyo3 python=3.11.7
激活虚拟环境:
conda activate pyo3
安装依赖:
pip install maturin
初始化项目:
maturin init
构建项目:
maturin develop
使用python调用这个库进行测试:
>>> import c01_hello_pyo3
>>> c01_hello_pyo3.sum_as_string(3,333)
Cargo.toml完整代码:
[package]
name = "c01_hello_pyo3"
version = "0.1.0"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[lib]
name = "c01_hello_pyo3"
crate-type = ["cdylib"]
[dependencies]
pyo3 = "0.20.0"
src/lib.rs完整代码:
use pyo3::prelude::*;
/// Formats the sum of two numbers as string.
#[pyfunction]
fn sum_as_string(a: usize, b: usize) -> PyResult<String> {
Ok((a + b).to_string())
}
/// A Python module implemented in Rust.
#[pymodule]
fn c01_hello_pyo3(_py: Python, m: &PyModule) -> PyResult<()> {
m.add_function(wrap_pyfunction!(sum_as_string, m)?)?;
Ok(())
}