为了创建一个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(())
}发布于 2021-05-26 15:49:15
宏不能共享其参数或状态。如果不想重复标识符,请将mymodule定义移动到create_python_function宏中,然后将该宏更改为使用repetitions (The Rust Reference)
macro_rules! create_python_function {
($($name:ident => $objtype:ty),* $(,)?) => {
$(
paste! {
#[pyclass(unsendable)]
pub struct [<$name PyIface>] {
obj: GenericStruct<$objtype>,
}
impl [<$name PyIface>]{
pub fn new() -> [<$name PyIface>]{
[<$name PyIface>] { obj: todo!() }
}
}
pub fn [<create_object_ $name>]() -> [<$name PyIface>]{
[<$name PyIface>]::new()
}
}
)*
#[pymodule]
fn mymodule(_py: Python, m: &PyModule) -> Result<(), ()> {
$(
paste! {
m.add_function(wrap_pyfunction!([<create_object_ $name>], m)?).unwrap();
}
)*
Ok(())
}
};
}
struct Foo;
create_python_function!(
foo => Foo,
v => Vec<()>,
);https://stackoverflow.com/questions/67625388
复制相似问题