贴一个 str到str和int到str的例子,比python的c扩展以及cython不知道舒服到哪里去了。传str足矣,别的我没研究了,class也能传,但是我一般降低复杂度,都是序列化json跨语言交互。
use pyo3::prelude::*;
use pyo3::wrap_pyfunction;
use pyo3::types::PyDict;
pub mod mylibs;
// 可以做成whl格式,太方便了pip install maturin 根目录maturin build
#[pyfunction]
fn int_str(a: usize, b: usize) -> PyResult<String> {
Ok((a + b).to_string())
}
#[pyfunction]
fn str_str(a: &str) -> PyResult<String> {
let b=mylibs::myjson::_s2s(a);
Ok(b)
}
#[pyfunction(kwds="**")]
fn num_kwds(kwds: Option<&PyDict>) -> usize {
kwds.map_or(0, |dict| dict.len())
}
#[pymodule]
fn string_sum(_py: Python, m: &PyModule) -> PyResult<()> {
m.add_wrapped(wrap_pyfunction!(int_str))?;
m.add_wrapped(wrap_pyfunction!(str_str))?;
Ok(())
}
最为关键的是,可以通过一个工具一键生成whl包,具体可以根据名字查github。一般就这两句够了:
pip install maturin
maturin build
有可能提示找不到python解释器,即使python已经在path中,这个干:
maturin build --interpreter python
不仅连setup.py省了,连cargo都省了。见过爽的,没见过这么爽的。