如何创建Rust回调函数以传递给FFI函数? [英] How do I create a Rust callback function to pass to a FFI function?

查看:189
本文介绍了如何创建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));

这篇关于如何创建Rust回调函数以传递给FFI函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆