问题描述
为了创建一个使用 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(())
}
解决方法
宏不能共享它们的参数或状态。
如果您不想重复标识符,请将 var searchView = menu.findItem(R.id.action_search).actionView as SearchView
searchView.isIconified = true
定义移动到 mymodule
宏中并将宏更改为使用 repetitions (The Rust Reference)
create_python_function