[Solved] Closure can't access its environment


#1

Lately I’m working on some FFI stuff, a wrapper for libsoundio to be exact, and after some initial trouble with unsafe and pointer casts the sound output finally works :sweat_smile: . A big issue is still open, because library users should be able to register closures as callbacks.
I can already register a callback closure (that is called from wrapper function that translates the C callback), but it can’t access values from it’s environment (which is one of the main reasons to use closures in the first place).
I’ve created a small playpen to demonstrate the problem.
Thanks in advance.


#2

I’ve already figured out how to fix the problem, here is the working playpen.

The closure couldn’t access its environment because it was casted to a plain function pointer through the double *const like you can see in the following lines.
Of course, the dereferencing of *(*cb) had to be changed, too.

    let cb = void_ptr as *const *const T;
    let callback = unsafe { &*(*cb) as &T };

Here is the working solution:

    let cb = void_ptr as *const T;
    let callback = unsafe { &*cb as &T };

#3

Be careful with lifetimes here. If the lifetime of the closure is not tied to the lifetime of the context you’re placing it into, it has to be 'static:

fn runner<T: Fn(&str) + 'static>(f: Box<T>) {