我正在尝试使用 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]
usesmy_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/