Unboxed Closures and FFI Callbacks
aatch.github.io/blog/2015/01/17/unboxed-closu...Posted Jan 16, 2015, 11:45 PM UTC
127
Posted Jan 16, 2015, 11:45 PM UTC
let opt_closure = closure as *mut Option<F>;
Hmm, does that seem right? It's not a pointer to an optional closure. Perhaps it should instead be a Option<&F>?
If I try to run the code as is it panicks, but this works:
let opt_closure = (closure as *const F).as_ref();
let res = opt_closure.unwrap()(a as i32, b as i32);
Yeah, I also wondered about that...
Oh my gosh - the amount of pain I went through with glfw-rs' callbacks was astounding. Thank goodness for unboxed closures!
Thanks again for this :)
I claim prior art! :) https://github.com/mzabaluev/grust/blob/2920e89d7ad38feb8a76828403c98ccea5397f30/fauxgen/gio.rs#L201
Thanks to the author for this writeup.
Well I pulled this pattern out of the standard library, so I can't take credit anyway.
Why do you
takethe closure? The effect I can see it having is preventing multiple calls, which, since this is aFnand not aFnOnce, I don't see why you'd do that. It also putsfin an invalid state, which doesn't seem right.