Skip to content

Instantly share code, notes, and snippets.

@mqudsi
Created December 23, 2018 00:30
Show Gist options
  • Save mqudsi/351f5794bb6cb496386e7bb42c5b709c to your computer and use it in GitHub Desktop.
Save mqudsi/351f5794bb6cb496386e7bb42c5b709c to your computer and use it in GitHub Desktop.
A rust snippet to convert an anonymous function (or closure?) into an FFI-compatible callback
use std::os::raw::c_void;
extern {
fn register_callback(callback: extern fn(*const c_void, u32), user: *const c_void);
}
fn register<F: Fn(u32)>(f: F) {
extern fn handler<F: Fn(u32)>(f_ptr: *const c_void, val: u32) {
let f = unsafe { &*(f_ptr as *const F) };
f(val)
}
unsafe {
register_callback(handler::<F>, Box::into_raw(Box::new(f)) as *const c_void);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment