我正在使用 Pyo3 从 Python 调用 Rust 函数,反之亦然。
我正在努力实现以下目标:
Python 调用
rust_function_1
Rust 函数
rust_function_1
调用 Python 函数python_function
,将 Rust 函数rust_function_2
作为回调参数传递Python 函数
python_function
调用回调,在本例中为 Rust 函数rust_function_2
我不知道如何rust_function_2
作为回调参数传递给python_function
.
我有以下 Python 代码:
import rust_module
def python_function(callback):
print("This is python_function")
callback()
if __name__ == '__main__':
rust_module.rust_function_1()
我有以下非编译 Rust 代码:
use pyo3::prelude::*;
#[pyfunction]
fn rust_function_1() -> PyResult<()> {
println!("This is rust_function_1");
Python::with_gil(|py| {
let python_module = PyModule::import(py, "python_module")?;
python_module
.getattr("python_function")?
.call1((rust_function_2.into_py(py),))?; // Compile error
Ok(())
})
}
#[pyfunction]
fn rust_function_2() -> PyResult<()> {
println!("This is rust_function_2");
Ok(())
}
#[pymodule]
#[pyo3(name = "rust_module")]
fn quantum_network_stack(_python: Python, module: &PyModule) -> PyResult<()> {
module.add_function(wrap_pyfunction!(rust_function_1, module)?)?;
module.add_function(wrap_pyfunction!(rust_function_2, module)?)?;
Ok(())
}
错误信息是:
error[E0599]: the method `into_py` exists for fn item `fn() -> Result<(), PyErr> {rust_function_2}`, but its trait bounds were not satisfied
--> src/lib.rs:10:37
|
10 | .call1((rust_function_2.into_py(py),))?;
| ^^^^^^^ method cannot be called on `fn() -> Result<(), PyErr> {rust_function_2}` due to unsatisfied trait bounds
|
= note: `rust_function_2` is a function, perhaps you wish to call it
= note: the following trait bounds were not satisfied:
`fn() -> Result<(), PyErr> {rust_function_2}: AsPyPointer`
which is required by `&fn() -> Result<(), PyErr> {rust_function_2}: pyo3::IntoPy<Py<PyAny>>`