python - Maturin 项目背后有 Python 绑定(bind)功能

标签 python rust pyo3 maturin

我正在尝试使用 maturin 和 PyO3 为 Rust 库编写可选的 Python 绑定(bind)。 maturin 创建的默认布局是

my-project
├── Cargo.toml
├── python
│   └── my_project
│       ├── __init__.py
│       └── bar.py
├── pyproject.toml
├── README.md
└── src
    └── lib.rs

其中所有 Rust 代码,包括 #[pymodule] 属性都进入 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 rir_generator(_py: Python, m: &PyModule) -> PyResult<()> {
    m.add_function(wrap_pyfunction!(sum_as_string, m)?)?;
    Ok(())
}

但是,由于我想将所有这些代码放在条件功能后面,因此我尝试将所有包装器代码放入 src/python.rs 中,然后将其导入 src/lib.rs 使用

#[cfg(feature = "python")]
pub mod python;

但是构建失败并出现警告

Warning: Couldn't find the symbol PyInit_my_project in the native library. Python will fail to import this module. If you're using pyo3, check that #[pymodule] uses my_project as module name

如果我将代码放回src/lib.rs,警告就会消失。

有没有办法将 PyO3 绑定(bind)放入子模块中,然后使用功能有条件地导入?

最佳答案

你就快到了。您需要将以下部分添加到 Cargo.toml删除警告。

[features]
default = ["python"]
python = []

引自documentation :

Features are defined in the [features] table in Cargo.toml. Each feature specifies an array of other features or optional dependencies that it enables.

默认情况下,除非显式启用,否则所有功能均被禁用。这将导致 native 库在不使用 PyInit_<module_name> 的情况下构建。符号,因此出现警告。 这个 可以通过指定 default feature 来更改

关于python - Maturin 项目背后有 Python 绑定(bind)功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/77286483/

相关文章:

python - Pyo3 中具有自引用的异步函数

python:从数据中随机抽样但保持相同的分布

scope - Rust 中看似矛盾的借用场景

rust - 为什么 Rust 书中的多线程 Web 服务器示例无法编译?

rust - 拥有一个值的一般方式(不要指定 `Rc` 或 `Box` )

python - 如何在Rust中将PyArray转换为Vec <Vec <T >>

asynchronous - Rust 显示预期的特征对象 `dyn Future` ,在将函数作为参数传递时发现不透明类型

python - Python 中的统计分析

使用 win32com 的 Python 不会使用所需的加载项更新 Excel 工作表

python - 绘制一个由 Xaolin Wu 描述的抗锯齿圆