通过 pio3 向 Python 公开 Rust Vec<>

Exposing Rust Vec<> to Python via pio3

提问人:Nikolay Shulga 提问时间:10/17/2023 更新时间:10/17/2023 访问量:18

问:

我正在尝试使用 pyo3 向 Python 公开这样的东西(为清楚起见进行了简化):

#[pyclass]
#[derive(Debug)]
pub struct Mesh {
    #[pyo3(get, set)]
    pub vertices : Vec<MeshVertex>,
    #[pyo3(get, set)]
    pub facets : Vec<MeshFacet>,
}

..这样,例如,在 Python 中附加一个对象将在 Rust Mesh 对象中更新。上面的代码没有这样做:Python Mesh 对象中的顶点似乎是 Rust 对象中顶点的副本,因此更新一个顶点不会对另一个顶点产生任何影响。verticesvertices

相关代码片段:

蟒:

mv = plugin_api.MeshVertex() 
# this updates vertices in the Rust object
mesh.push_vertex(mv)
# this has no effect on vertices in the Rust object
mesh.vertices.append(mv) 

一个将顶点附加到 Rust Mesh 对象的函数(确实有效,但这不是我要找的):

#[pymethods]
impl Mesh {
    #[new]
    fn new() -> Self { Mesh { facets: Vec::new(), vertices: Vec::new() } }
    fn push_vertex(&mut self, v:MeshVertex) {self.vertices.push(v)}

main.rs:

   let mesh = plugin.getattr("unit_mesh")?.call0()?;

        //now we extract (i.e. mutably borrow) the rust struct from python object
        {
            //this scope will have mutable access to the gadget instance, which will be dropped on
            //scope exit so Python can access it again.
            let mesh_rs: PyRef<'_, plugin_api::Mesh> = mesh.extract()?;
            // we can now modify it as if it was a native rust struct

            //which includes access to rust-only fields that are not visible to python
            println!("mesh vertices {:?}", mesh_rs.vertices);
        }

正如你所看到的,我对 Rust 和 pyo3 都相当陌生。先谢谢你。

PYO3型

评论


答: 暂无答案