首页 > 解决方案 > 使用 PyAny 将 Rust 创建的对象从 Python 传递回 Rust

问题描述

我在 Rust 中有一个 struct + 实现,我返回 Python。这个对象也可以传Rust 做进一步的工作。(在我的实际代码中,我使用的是 a HashMap<String, MyStruct>,但即使直接使用 struct 似乎也会导致相同的问题,因此我的示例使用struct Person简单。)

看来我需要impl FromPyObject for Person但 Rust 找不到方法PyAnydowncast

#[pyclass]
struct Person {
    name: String,
    age: u8,
    height_cm: f32,
}

impl pyo3::FromPyObject<'_> for Person {
    fn extract(any: &PyAny) -> PyResult<Self> {
        Ok(any.downcast().unwrap())
               ^^^^^^^^ method not found in `&pyo3::types::any::PyAny`
    }
}

#[pyfunction]
fn make_person() -> PyResult<Person> {
    Ok(Person {
        name: "Bilbo Baggins".to_string(),
        age: 51,
        height_cm: 91.44,
    })
}

#[pyfunction]
fn person_info(py:Python, p: PyObject) -> PyResult<()> {
    let p : Person = p.extract(py)?;
    println!("{} is {} years old", p.name, p.age);
    Ok(())
}

这是将 Rust 对象从 Python 传回 Rust 的正确方法吗?如果是这样,在这里使用的正确方法是PyAny什么?

标签: rustpyo3

解决方案


推荐阅读