Skip to content

Instantly share code, notes, and snippets.

@gliheng
Created January 12, 2019 04:44
Show Gist options
  • Save gliheng/08274910c3e3f45d4f1a79e62447b53b to your computer and use it in GitHub Desktop.
Save gliheng/08274910c3e3f45d4f1a79e62447b53b to your computer and use it in GitHub Desktop.
rust closure to C style function
use lazy_static::lazy_static;
use std::os::raw::{c_int};
use std::sync::Mutex;
use std::ffi::c_void;
lazy_static! {
static ref REAL_CALLBACK: Mutex<Option<Box<FnMut(c_int, c_int) -> c_int + Send>>> = Default::default();
}
extern "C" fn callback(x: c_int, y: c_int) -> c_int {
if let Some(ref mut real_callback) = *REAL_CALLBACK.lock().unwrap() {
real_callback(x, y)
} else {
panic!("<handle error here>");
}
}
fn main() {
*REAL_CALLBACK.lock().unwrap() = Some(Box::new(move |x, y| {
println!("Adding");
x + y
}));
unsafe {
call_c(callback);
}
}
pub type Callback = extern fn(c_int, c_int) -> c_int;
fn call_c(ptr: Callback) {
println!("ret: {}", ptr(10, 20));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment