How do I create a Rust callback function to pass to a FFI function? -


this how c api looks

void mosquitto_connect_callback_set(struct mosquitto *mosq, void (*on_connect)(struct mosquitto *, void *, int)); 

rust-bindgen has generated me

pub fn mosquitto_connect_callback_set(mosq: *mut struct_mosquitto,                                           on_connect:                                               ::std::option::option<extern "c" fn(arg1:                                                                                       *mut struct_mosquitto,                                                                                   arg2:                                                                                       *mut ::libc::c_void,                                                                                   arg3:                                                                                       ::libc::c_int) -> ()>) 

how create rust callback function pass on_connect parameter in above rust binding?

how create rust callback function?

have read the rust programming language, section ffi titled callbacks c code rust functions?

the example there is

extern fn callback(a: i32) {     println!("i'm called c value {0}", a); }  #[link(name = "extlib")] extern {    fn register_callback(cb: extern fn(i32)) -> i32;    fn trigger_callback(); }  fn main() {     unsafe {         register_callback(callback);         trigger_callback(); // triggers callback     } } 

for specific case, know specific type of function need:

extern "c" fn mycallback(arg1: *mut struct_mosquitto,                          arg2: *mut ::libc::c_void,                          arg3: ::libc::c_int) -> () {     println!("i'm in rust!"); } 

and use like

mosquitto_connect_callback_set(mosq, some(mycallback)); 

Comments