Hello !
I am trying to make my Rust library interact with C, and I ran into an weird case.
I have the following rust code :
struct Caller<F: Fn()> {
function: F,
}
impl<F: Fn()> Caller<F> {
fn call(&self) {
(self.function)()
}
}
And my goal is to expose the Caller
struct to C : but
- This code fails to compile because
extern "C" fn()
does not implementFn()
type Callback = extern "C" fn();
#[no_mangle]
extern "C" fn create_caller(function: Callback) -> *mut Caller<Callback> {
Box::leak(Box::new(Caller { function }))
}
- And this one warns me that
Caller<impl Fn()>
is not ffi-safe
type Callback = extern "C" fn();
#[no_mangle]
extern "C" fn create_caller(function: Callback) -> *mut Caller<impl Fn()> {
Box::leak(Box::new(Caller {
function: move || function(),
}))
}
Is the second version correct, despite the warning? Or is there a third, better way to do ?