在项目中经常会看到一些callback函数,callback函数实现了用户自定义处理
主要表现在C语言的面向对象编程、异步处理
C语言中的callback函数的实现,主要是利用了函数指针
废话不多说,直接贴代码
#include<stdio.h>
#include<string.h>
typedef struct{
int calc_max;
int calc_sum;
int (*calc_get_max)(int x, int y);
int (*calc_get_sum)(int x, int y);
}calculate_t;
typedef void (*callback_function)(int index, int* array, int* out);
static int get_max(int a, int b)
{
return a > b? a:b;
}
static int get_sum(int a, int b)
{
return a + b;
}
static void my_get_array_elem(int index, int* array, int *out)
{
*out = array[index];
}
int calculate_test(calculate_t* calc, int a, int b)
{
int sum = a + b;
int max = a > b ? a : b;
printf("right: sum = %d, max = %d\n", sum, max);
calc->calc_sum = calc->calc_get_sum(a, b);
calc->calc_max = calc->calc_get_max(a, b);
if ((sum == calc->calc_sum) && (max == calc->calc_max))
{
return 1;
}
return 0;
}
int array_iterator(int index, int* array, callback_function get_array_elem)
{
int elem = 0;
get_array_elem(index, array, &elem);
return elem;
}
int main(int argc, char** argv)
{
int a = 10;
int b = 9;
int index = 0;
calculate_t calc = {0};
int array[] = {78, 56, 54, 41, 62, 25, 10};
memset(&calc, 0, sizeof(calc));
calc.calc_get_max = get_max;
calc.calc_get_sum = get_sum;
if (1 == calculate_test(&calc, a, b))
{
printf("calc: sum = %d, max = %d\n", calc.calc_sum, calc.calc_max);
}
else
{
printf("calc error\n");
}
for (index = 0; index < sizeof(array)/sizeof(int); index++)
{
printf("right: array[%d] = %d ", index, array[index]);
printf("my: array[%d] = %d\n", index, array_iterator(index, array, my_get_array_elem));
}
return 0;
}
上面的代码并没有给出callback函数在异步处理上的表现,Unix中信号处理机制、和一些第3方的开源库实现的事件驱动机制都可以认为是异步处理,都是注册某个信号处理和事件处理函数