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