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

问题描述 投票:0回答:1

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

struct Person
。)

看来我需要

impl FromPyObject for Person

,但是Rust找不到

PyAny
downcast
方法


#[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

的正确方法是什么?

    

rust pyo3
1个回答
0
投票

#[pyclass] struct Person { name: String, age: u8, height_cm: f32, } #[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: Bound<'_, Person>) -> PyResult<()> { // ^^^^^ ^^^^^ enter code here let p = p.borrow(); // immutably borrow the inner value println!("{} is {} years old", p.name, p.age); Ok(()) }

	
© www.soinside.com 2019 - 2024. All rights reserved.