callback函数详解

在项目中经常会看到一些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方的开源库实现的事件驱动机制都可以认为是异步处理,都是注册某个信号处理和事件处理函数

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值