【发布时间】:2021-05-20 17:34:48
【问题描述】:
为了创建一个使用泛型类型的结构的 pyo3 驱动的 Python 类,我想使用包装器来生成不需要为每个特定类型执行此操作的代码。
我创建了一个生成代码的宏,但我需要将我的宏生成的函数注册为 Python 模块的函数。
一种方法是跟踪宏中使用的标识以使用它们并使用另一个宏生成wrap_pyfunction,但我找不到任何相关内容。
(当然,任何其他生成代码的解决方案都会受到热烈欢迎)
我现在拥有的(简化的)代码:
macro_rules! create_python_function {
($name:ident, $objtype:expr) => {
paste!{
#[pyclass(unsendable)]
pub struct [<$name PyIface>] {
obj: GenericStruct<$objtype>,
}
impl [<$name PyIface>]{
pub fn new() -> [<$name PyIface>]{
[<$name PyIface>] {}
}
}
pub fn [<create_object_ $name>]() -> [<$name PyIface>]{
[<$name PyIface>]::new()
}
}
};
}
create_python_function!(name, SpecificType);
#[pymodule]
fn mymodule(_py: Python, m: &PyModule) -> PyResult<()> {
/* I want to auto-generate this with macro
* m.add_function(wrap_pyfunction!(create_object_name, m)?).unwrap();
*/
Ok(())
}
【问题讨论】:
-
您可以在宏定义中定义宏,调用外部宏后即可使用。内部宏定义可以使用外部宏定义的参数。虽然我不确定这是否是您需要的。
-
不,但很有趣,谢谢。我想要的是调用一堆“create_python_function”宏,并在pymodule中只调用一个“wrap_created_python_functions”,它会为我之前调用的“create_python_function”的每个标识生成1行代码。我需要记住 create_python_function 宏中使用的所有 $name ident 并使用它来生成最终包装(希望我足够清楚)
标签: rust macros pyo3 rust-decl-macros