-
Here is an example what I would like to achieve, of course this is just a psudo code that doesn't work. Python class with a function that should be called from rust with a callback parameter. class Test:
def test_fn(callback):
a = 1
print(f"value a from python {a}")
callback(a)
b = 2
print(f"value b from python {b}")
callback(b) Rust that just loads a class and calls a method and passing our callback function. fn my_callback(value: u32) {
println!("value from rust: {}", value);
}
pub fn cllback_test() -> PyResult<()> {
let py_test_path = include_str!(concat!(
env!("CARGO_MANIFEST_DIR"),
"/test.py"
));
Python::with_gil(|py| -> PyResult<()> {
let test_class = PyModule::from_code(py, py_test_path, "", "")?
.getattr("Test")?;
test_class.call_method1("test_fn", (my_callback))?;
Ok(())
})?;
Ok(())
} The main Idea is that I want to be able to emit/callback some values at some point from python, I don't want to return them at the end of the function but use callback so I can emit multiple values at different times. Maybe this is not the correct approach but I wanted to give an example to what I would like to achieve. Also I am new to pyo3 so currently I am not using maturin, just the pyo3 library and if possible would like to stick as similar as the way I am showing if possible, if it is not would appreciate any tips. |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
you can make a closure with https://docs.rs/pyo3/latest/pyo3/types/struct.PyCFunction.html#method.new_closure or create a pyclass that implements |
Beta Was this translation helpful? Give feedback.
you can make a closure with https://docs.rs/pyo3/latest/pyo3/types/struct.PyCFunction.html#method.new_closure or create a pyclass that implements
__call__
.