当前位置: 首页 > article >正文

使用rust语言创建python模块(pyo3+maturin)

1. 首先使用conda创建python虚拟环境(已创建的可省略)

>conda create --prefix=E:\python_envs\rust_python python=3.11

2. 激活python虚拟环境

conda activate rust_python

3. 安装maturin

pip install maturin

4. 创建rust项目

>cd  E:\python_envs\rust_python
>mkdir rust
>cd rust
>maturin init
✔ 🤷 Which kind of bindings to use?
  📖 Documentation: https://maturin.rs/bindings.html · pyo3
  ✨ Done! Initialized project E:\python_envs\rust_python\rust

选择pyo3,将在E:\python_envs\rust_python\rust\创建rust项目

5. 在Visual Studio Code中打开rust项目并编辑 

以pyo官方示例为例,修改Cargo.toml文件内容如下:

[package]
name = "rust"
version = "0.1.0"
edition = "2021"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[lib]
# The name of the native library. This is the name which will be used in Python to import the
# library (i.e. `import string_sum`). If you change this, you must also change the name of the
# `#[pymodule]` in `src/lib.rs`.
name = "rust_string_sum"
# "cdylib" is necessary to produce a shared library for Python to import from.
#
# Downstream Rust code (including code in `bin/`, `examples/`, and `tests/`) will not be able
# to `use string_sum;` unless the "rlib" or "lib" crate type is also included, e.g.:
# crate-type = ["cdylib", "rlib"]
crate-type = ["cdylib"]

[dependencies]
pyo3 = { version = "0.23.3", features = ["extension-module"] }

保存后,VS Code的rust-analyzer插件将自动运行Cargo下载pyo3及相关依赖包(过程可能会比较长)。

 修改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. The name of this function must match
/// the `lib.name` setting in the `Cargo.toml`, else Python will not be able to
/// import the module.
#[pymodule]
fn rust_string_sum(m: &Bound<'_, PyModule>) -> PyResult<()> {
    m.add_function(wrap_pyfunction!(sum_as_string, m)?)?;
    Ok(())
}

6. 使用maturin编译项目并安装到python环境

>maturin develop
  Downloaded portable-atomic v1.10.0
  Downloaded 1 crate (174.8 KB) in 18.31s
🔗 Found pyo3 bindings
🐍 Found CPython 3.11 at E:\python_envs\rust_python\python.exe
📡 Using build options features from pyproject.toml
   Compiling once_cell v1.20.2
   Compiling cfg-if v1.0.0
   Compiling unindent v0.2.3
   Compiling libc v0.2.168
   Compiling pyo3-build-config v0.23.3
   Compiling memoffset v0.9.1
   Compiling pyo3-macros-backend v0.23.3
   Compiling pyo3-ffi v0.23.3
   Compiling pyo3 v0.23.3
   Compiling pyo3-macros v0.23.3
   Compiling rust v0.1.0 (E:\python_envs\rust_python\rust)
    Finished `dev` profile [unoptimized + debuginfo] target(s) in 5.56s
📦 Built wheel for CPython 3.11 to C:\Users\yislwll\AppData\Local\Temp\.tmpRW3z8Z\rust-0.1.0-cp311-cp311-win_amd64.whl
✏️  Setting installed package as editable
🛠 Installed  rust-0.1.0

7. 在python虚拟环境中调用rust新建的模块

(E:\python_envs\rust_python) E:\python_envs\rust_python\rust>python
Python 3.11.7 | packaged by conda-forge | (main, Dec 23 2023, 14:27:59) [MSC v.1937 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import rust_string_sum
>>> rust_string_sum.sum_as_string(5,20)
'25'
>>>


http://www.kler.cn/a/442656.html

相关文章:

  • STM32 FreeRTOS 的任务挂起与恢复以及查看任务状态
  • Windows图形界面(GUI)-QT-C/C++ - Qt图形绘制详解
  • Android 15应用适配指南:所有应用的行为变更
  • 【TI毫米波雷达】DCA1000不使用mmWave Studio的数据采集方法,以及自动化实时数据采集
  • 大语言模型的稀疏性:提升效率与性能的新方向
  • 2025-微服务—SpringCloud-1~3
  • spring RestTemplate使用说明
  • c语言中的信号处理:学习<signal.h>
  • 鸿蒙元服务项目实战:备忘录UI页面开发
  • 获取github容器注册表
  • 统计字符的个数C++
  • 正则表达式在线校验(RegExp) - 加菲工具
  • 微软商店错误提示的全方位解决方案
  • Vue项目的iconfont引入
  • Go语言开发入门与实战
  • 【踩坑】pip离线+在线在虚拟环境中安装指定版本cudnn攻略
  • java二分查找算法详解
  • wireshark功能块
  • 一分钟上手:如何创建你的第一个 Spring Boot Starter
  • Python:利用蒙特卡洛方法求解圆周率
  • CSS系列(21)-- Houdini 详解
  • 【Figma_01】Figma软件初始与使用
  • C++【默认成员函数(下)】
  • C++STL之list(用法超详解)
  • 一款可以替代Navicat的数据库管理工具
  • java: 无效的目标发行版: 9或警告: 源发行版 9 需要目标发行版 9