Skip to content

Pass a mutable reference #4230

Discussion options

You must be logged in to vote

Yes, it's possible to receive a mutable reference to a pyclass struct: https://pyo3.rs/v0.21.2/class#bound-and-interior-mutability

Doing like this works: Thank you very much @alex

use pyo3::prelude::*;

#[pyclass]
struct MyClass {
    pub inner: i32,
}

#[pymethods]
impl MyClass {
    #[new]
    fn new(value: i32) -> Self {
        MyClass { inner: value }
    }

    fn show(&self) {
        println!("MyClass: {}", self.inner);
    }
}


#[pyfunction]
fn adapt(x: &mut MyClass) {
    x.inner = 42;
}

#[pymodule]
fn foo_rs(m: &Bound<'_, PyModule>) -> PyResult<()> {
    m.add_class::<MyClass>()?;
    m.add_function(wrap_pyfunction!(adapt, m)?)?;
    Ok(())
}
from foo_rs import adapt, MyClass

Replies: 1 comment 5 replies

Comment options

You must be logged in to vote
5 replies
@therealevahill
Comment options

@alex
Comment options

alex Jun 3, 2024
Collaborator

@therealevahill
Comment options

@therealevahill
Comment options

Answer selected by therealevahill
@therealevahill
Comment options

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
2 participants