Rust 编写 Python 拓展 Whl文件

pyo3 官方使用手册: 【点击查看】
maturin 构建使用工具: 【点击查看】

一、前言

安装 pip install maturin
主要有以下三个命令:

  • maturin publish 将 crate 构建到 python 包中并将它们发布到 pypi。

  • maturin build构建轮子并将它们存储在一个文件夹中(target/wheels默认情况下),但不上传它们。可以使用twine上传那些。

  • maturin develop构建 crate 并将其作为 python 模块直接安装在当前 virtualenv 中。请注意,虽然maturin develop速度更快,但它并不支持运行pip install后maturin build支持的所有功能。
    pyo3并rust-cpython自动检测绑定,对于 cffi 或二进制文件,您需要通过-b cffi或-b bin. maturin 不需要额外的配置文件,也不会与现有的 setuptools-rust 或 Milksnake 配置冲突。您甚至可以将其与测试工具(例如tox )集成。test-crates文件夹中有不同绑定的示例。

    包的名称将是货物项目的名称,即在名称字段[package]的部分Cargo.toml。导入时使用的模块名称将是name该[lib]部分中的值(默认为包的名称)。对于二进制文件,它只是由货物生成的二进制文件的名称。

1.1 官方示例

Cargo.tmol

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

[dependencies.pyo3]
version = "0.13.2"
features = ["extension-module"]

lib.rs

use pyo3::prelude::*;
use pyo3::wrap_pyfunction;

/// 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 string_sum(_py: Python, m: &PyModule) -> PyResult<()> {
    m.add_function(wrap_pyfunction!(sum_as_string, m)?)?;
    Ok(())
}

生成 whl 文件
执行开发编译 maturin build --interpreter python
执行发布编译 maturin build --release --interpreter python

安装并测试

cd target\wheels
pip install string_sum-0.1.0-cp37-none-win_amd64.whl

在这里插入图片描述

其它参考
https://blog.csdn.net/wangmarkqi/article/details/104618641
https://blog.csdn.net/muzico425/article/details/103331676

转自:https://blog.csdn.net/wsp_1138886114/article/details/118221227

posted @ 2022-10-14 10:46  MasonLee  阅读(236)  评论(0编辑  收藏  举报