[英]How do I create a Rust callback function to pass to a FFI function?
This is how the C API looks这是 C API 的样子
void mosquitto_connect_callback_set(struct mosquitto *mosq, void (*on_connect)(struct mosquitto *, void *, int));
rust-bindgen
has generated this for me 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,
) -> (),
>,
)
How do I create a Rust callback function to pass to the on_connect
parameter in the above Rust binding?如何创建 Rust 回调函数以传递给上述 Rust 绑定中的
on_connect
参数?
The Rust Programming Language , first edition , has a section about FFI titled Callbacks from C code to Rust functions . Rust 编程语言,第一版,有一个关于 FFI 的部分,标题为从 C 代码到 Rust 函数的回调。
The example from there is那里的例子是
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!");
}
And then use it like然后像这样使用它
mosquitto_connect_callback_set(mosq, Some(mycallback));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.