Linux C 回调(callback)函数

callback:即回调函数,是一个通过函数指针调用的函数。如果你把函数的指针(地址)作为参数传递给另一个函数,当这个指针被用为调用它所指向的函数时,我们就说这是回调函数。回调函数不是由该函数的实现方直接调用,而是在特定的事件或条件发生时由另外的一方调用的,用于对该事件或条件进行响应。
实例如下:
callback.h中声明callback函数:

#ifndef __CALLBACK_H__
#define __CALLBACK_H__
#ifdef __cplusplus
extern "C" {
#endif

typedef void(*callback_t)(int event_id, int value1, int value2, unsigned char *buffer, int buffer_size); /* callback函数定义 */

void set_callback(callback_t callback);
void do_something();

#ifdef __cplusplus
}
#endif
#endif	// __CALLBACK_H__

main.c实现callback函数do_notify(),将函数指针通过set_callabck()传递

#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>
#include "callback.h"

void do_notify(int event_id, int value1, int value2, unsigned char *buffer, int buffer_size)
{
    printf("event_id: %d, value1: %d, value: %d, buffer: %s, buffer_size: %d\n", event_id, value1, value2, buffer, buffer_size  );
}

int main(int argc, char const *argv[])
{
    set_callback(do_notify);

    do_something();

    return 0;
}

callback.c中实现callback函数的调用

#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>
#include "callback.h"

static callback_t g_notify;

void set_callback(callback_t callback)
{
    g_notify = callback;
}

void do_something()
{
    char *buf = "vegeta";

    g_notify(0, 1, 2, buf, strlen(buf));
}

调用g_notify会在main.c中的do_notify打印出来,结果如下:
event_id: 0, value1: 1, value: 2, buffer: vegeta, buffer_size: 6

  • 3
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值