如何创建Rust回调函数以传递给FFI函数?

问题描述:

这是C API的外观

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

rust-bindgen为我生成了此

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,
        ) -> (),
    >,
)

如何创建Rust回调函数以传递给上述Rust绑定中的on_connect参数?

How do I create a Rust callback function to pass to the on_connect parameter in the above Rust binding?

Rust编程语言 第一版,其中包含有关FFI的部分,标题为

The Rust Programming Language, first edition, has a section about FFI titled Callbacks from C code to Rust functions.

那里的例子是

extern "C" fn callback(a: i32) {
    println!("I'm called from C with value {0}", a);
}

#[link(name = "extlib")]
extern "C" {
    fn register_callback(cb: extern "C" fn(i32)) -> i32;
    fn trigger_callback();
}

fn main() {
    unsafe {
        register_callback(callback);
        trigger_callback(); // Triggers the callback
    }
}

对于您的特定情况,您已经知道所需的特定功能类型:

For your specific case, you already know the specific type of function you need:

extern "C" fn mycallback(
    arg1: *mut Struct_mosquitto,
    arg2: *mut ::libc::c_void,
    arg3: ::libc::c_int,
) -> () {
    println!("I'm in Rust!");
}

然后像使用它

mosquitto_connect_callback_set(mosq, Some(mycallback));