使用多参数函数作为回调函数

ryo*_*ait 3 c function-pointers

我在C中使用一个与系统相关的计时器(我无法更改其代码).我可以使用此功能访问它,其中包括:

void start_timer(int duration, void (*callback)(void*), void* arg);
Run Code Online (Sandbox Code Playgroud)

所以我可以给定时器一个回调函数及其void*参数.

我想用作回调的函数是:

void send_message(ipaddr* source, ipaddr* destination, char* message);
Run Code Online (Sandbox Code Playgroud)

我不能直接给这个函数start_timer,因为它与void (*)(void*)所需的类型不匹配.由于C中不存在匿名函数,我无法使用此解决方案(但这是我想要做的):

start_timer(1000, void(*)(void* stuff){
    send_message(source, destination, message);
}, NULL);
Run Code Online (Sandbox Code Playgroud)

所以我必须给这个函数命名:

void call_send_message(void* stuff) {
    send_message(source, destination, message);
}
start_timer(1000, &call_send_message, NULL);
Run Code Online (Sandbox Code Playgroud)

是否有更美妙的方式来调用send_message函数start_timer

Jit*_*ite 5

创建一个struct这样的东西:

struct args {
    ipaddr *source;
    ipaddr *destination;
    char *message;
};
Run Code Online (Sandbox Code Playgroud)

并让你的send_message函数接受void*参数,然后你只需将它转换为一个struct args类型,然后你可以访问它的成员.如果你不能编辑它,那么像你的例子一样创建一个"包装器":

所以基本上你的功能如下

void call_send_message(void* stuff) {
    send_message(source, destination, message);
}
Run Code Online (Sandbox Code Playgroud)

void call_send_message(void* stuff) {
    struct args *realstuff = (struct args *) stuff;
    send_message(realstuff->source, realstuff->destination, realstuff->message);
}
Run Code Online (Sandbox Code Playgroud)