rust - 使用 PyAny 将 Rust 创建的对象从 Python 传递回 Rust
问题描述
我在 Rust 中有一个 struct + 实现,我返回 Python。这个对象也可以传回Rust 做进一步的工作。(在我的实际代码中,我使用的是 a HashMap<String, MyStruct>
,但即使直接使用 struct 似乎也会导致相同的问题,因此我的示例使用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
什么?
解决方案
推荐阅读
- docker - 如何在 docker 的容器 A 中调用命令的容器 B
- android - 找不到符号类 OnCompleteListener
- freebsd - FreeBSD 11 Beaglebone 启用 UART1 和 UART4
- python - 在一张图像中裁剪多个边界框的最有效/最快的方法,超过数千张图像?
- apache-spark - 如何在另一个数据框中从 JSON 创建数据框?
- html - 如何修复悬停未激活
- postgresql - 如何从 Windows 10 docker 上的 tar 文件恢复 postgres 数据
- sql - 将对角线样式行转换为单行
- html - 需要帮助以更好地理解 html5 上的 ul 标签
- c# - 在一个类中保存多个类的不同属性