maturin 简单试用

前边也简单介绍了maturin 是pyo3 推荐的rust python 模块开发首选工具,以下是一个简单的试用

项目准备

  • 初始化项目
mkdir  first
cd first
python -m venv venv
source venv/bin/activate
pip install maturin
maturin init
  • 项目结构
├── Cargo.lock
├── Cargo.toml
├── app.py
├── pyproject.toml
└── src
    └── lib.rs
  • 代码简单说明
    app.py 是调用开发的模块的,src/lib.rs 是基于pyo3 开发的模块,属于一个动态链接库,pyproject.toml 是推荐的python pip 包开发定义(新版本的)
    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 first(_py: Python, m: &PyModule) -> PyResult<()> {
    //  注册函数
    m.add_function(wrap_pyfunction!(sum_as_string, m)?)?;
    Ok(())
}

Cargo.toml cargo 配置,主要是pyo3 依赖以及模块类型说明(动态链接库)

[package]
name = "first"
version = "0.1.0"
edition = "2021"
 
[lib]
name = "first"
crate-type = ["cdylib"]
 
[dependencies]
pyo3 = "0.20.0"

pyproject.toml pip 模块定义(定义了后端使用maturin)

[build-system]
requires = ["maturin>=1.4,<2.0"]
build-backend = "maturin"
 
[project]
name = "first"
requires-python = ">=3.8"
classifiers = [
    "Programming Language :: Rust",
    "Programming Language :: Python :: Implementation :: CPython",
    "Programming Language :: Python :: Implementation :: PyPy",
]
dynamic = ["version"]
 
[tool.maturin]
features = ["pyo3/extension-module"]

app.py 主要是对于模块的使用

import first;
result = first.sum_as_string(1,3)
print(result)

构建

maturin 提供了不少命令,我们主要使用的是init ,develop,build,publish 等一些命令

  • 开发模式
maturin develop
  • 构建
maturin build  --releases
  • 运行效果
python app.py

一些问题

  • Caused by: Both VIRTUAL_ENV and CONDA_PREFIX are set. Please unset one of them

比如同时使用了虚拟环境,而且电脑也安装了conda 就会提示这个,解决方法,可以临时移除conda 的环境变量
如下

说明

以上是基于cli 工具提供的简单示例,实际上rust 与python 的交互设计的方面很多,可以好好研究下pyo3 rust 包

参考资料

https://www.maturin.rs/
https://github.com/PyO3/maturin
https://github.com/PyO3/pyo3

posted on 2023-12-19 10:44  荣锋亮  阅读(186)  评论(0编辑  收藏  举报

导航