使用 PyAny 将 Rust 创建的对象从 Python 传递回 Rust

use*_*321 5 rust pyo3

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

看来,我需要impl FromPyObject for Person,但锈找不到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(())
}
Run Code Online (Sandbox Code Playgroud)

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