I'm trying to expose something like this (simplified for clarity) to Python using pyo3:
#[pyclass]
#[derive(Debug)]
pub struct Mesh {
#[pyo3(get, set)]
pub vertices : Vec<MeshVertex>,
#[pyo3(get, set)]
pub facets : Vec<MeshFacet>,
}
.. such that appending an object to, e.g., vertices
in Python would update vertices
in the Rust Mesh object. The code above doesn't do that: vertices in the Python Mesh object seem to be a copy of vertices in the Rust object, so updating one won't have any effect on the other.
Relevant code snippets:
Python:
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)
A function to append a vertex to the Rust Mesh object (that does work, but it isn't what I'm looking for):
#[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);
}
As you can see, I'm fairly new to both Rust and pyo3. Thank you in advance.