Help about calling Rust from Python

I'm leaning how to call Rust from Python project.
I have trait in Rust code:

pub trait GetCloure {
    fn get_cloure(&self) -> impl Fn(i32) -> i32;
}

fn calc_cloure_for_py_obj(data: PyAny) -> Vec<i32> {
    let cloure = data.into_python_object().get_cloure();
    (0..10)
        .map(cloure)
        .collect::<Vec<_>>()
}

For example, I can implement this trait to a type:

pub struct MyStruct {
    pub data: i32,
}

impl GetCloure for MyStruct {
    fn get_cloure(&self) -> impl Fn(i32) -> i32 {
        let data = self.data;
        move |i: i32| {
            data + i
        }
    }
}

But how can I do the same thing in Python?

class MyStruct:
    
    def __init__(self, data):
        self.data = data
        
    def get_cloure(self): # should return Rust Cloure: impl Fn(i32) -> i32
        # return lambda i: self.data + i
        pass

So I can do something like this in Python:

rust_res_obj = rust.calc_cloure_for_py_obj(MyStruct(10))

The process of making your Rust function callable from Python involves using a Foreign Function Interface (FFI). I recommend checking out the guide by @Michael-F-Bryan:

2 Likes

Consider generating Python bindings for your Rust code using PyO3: pyo3 - Rust .

2 Likes

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.