如何从Rust宏生成的代码二次开发宏 实现pyo3模块函数自动注册
解决方案
你可以通过两种常用方式实现自动注册,不需要手动为每个生成的函数写注册代码:
方案1:集中式批量宏(无额外依赖,推荐)
把所有需要生成绑定的类型统一放在同一个宏里声明,宏一次性展开生成所有绑定类、创建函数,以及对应的注册代码。同时修正你原宏的参数匹配问题:$objtype是类型,应该用ty匹配器而不是expr。
use pyo3::prelude::*; use paste::paste; // 这里是你自己定义的泛型Rust结构体,提前声明即可 struct GenericStruct<T> { // 你的结构体字段 } macro_rules! register_py_types { // 匹配所有传入的 (绑定名, 具体类型) 对,支持末尾加逗号 ($(($name:ident, $objtype:ty)),* $(,)?) => { // 1. 展开生成每个类型对应的Py类和创建函数 $( paste!{ #[pyclass(unsendable)] pub struct [<$name PyIface>] { obj: GenericStruct<$objtype>, } // 要暴露给Python的方法必须放在#[pymethods]块内 #[pymethods] impl [<$name PyIface>]{ #[new] pub fn new() -> Self { Self { obj: GenericStruct {} } } } // 要注册的函数必须加#[pyfunction]属性 #[pyfunction] pub fn [<create_object_ $name>]() -> [<$name PyIface>]{ [<$name PyIface>]::new() } } )* // 2. 自动生成模块注册逻辑,批量添加所有函数和类 #[pymodule] fn mymodule(_py: Python, m: &PyModule) -> PyResult<()> { $( paste!{ m.add_function(wrap_pyfunction!([<create_object_ $name>], m)?)?; // 顺便把Py类也注册到模块,否则Python侧看不到类定义 m.add_class::<[<$name PyIface>]>()?; } )* Ok(()) } }; } // 所有需要生成绑定的类型都在这里声明即可,新增直接加行 register_py_types!( (name, SpecificType), (another_name, AnotherSpecificType) );
后续新增类型只要在register_py_types!里加一行配置,不需要修改其他代码。
方案2:分散式自动收集注册
如果需要在不同代码位置分散调用生成宏,可以用inventory库实现编译期自动收集所有注册项,不需要集中声明。
- 先添加依赖到Cargo.toml:
[dependencies] inventory = "0.3"
- 代码实现:
use pyo3::prelude::*; use paste::paste; use inventory::collect; struct GenericStruct<T> {} // 定义注册项结构体,存每个函数/类的注册逻辑 struct PyBindRegister { register: fn(&PyModule) -> PyResult<()>, } // 声明全局收集器 collect!(PyBindRegister); macro_rules! create_python_function { ($name:ident, $objtype:ty) => { paste!{ #[pyclass(unsendable)] pub struct [<$name PyIface>] { obj: GenericStruct<$objtype>, } #[pymethods] impl [<$name PyIface>]{ #[new] pub fn new() -> Self { Self { obj: GenericStruct {} } } } #[pyfunction] pub fn [<create_object_ $name>]() -> [<$name PyIface>]{ [<$name PyIface>]::new() } // 把当前绑定的注册逻辑提交到全局收集器 inventory::submit! { PyBindRegister { register: |m: &PyModule| { m.add_function(wrap_pyfunction!([<create_object_ $name>], m)?)?; m.add_class::<[<$name PyIface>]>()?; Ok(()) } } } } }; } // 可以在任意位置分散调用宏,不需要集中管理 create_python_function!(name, SpecificType); create_python_function!(another_name, AnotherSpecificType); #[pymodule] fn mymodule(_py: Python, m: &PyModule) -> PyResult<()> { // 遍历所有收集到的注册项执行注册 for reg in inventory::iter::<PyBindRegister> { (reg.register)(m)?; } Ok(()) }
内容的提问来源于stack exchange,提问作者litchipi
相关产品推荐
相关产品推荐

