Created
December 23, 2018 00:30
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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