回调函数的注册和回调

函数注册和回调函数
1、什么是函数注册和回调
回调函数无非是对函数指针的应用,说白了就是通过使用函数指针来调用一个函数,而函数注册就是把函数指针作为参数传递出去便于别的模块使用的过程。所以函数注册就是为了回调,先注册再回调。

2、为什么要使用回调函数
回调函数可以把调用者与被调用者分开,所以调用者不关心谁是被调用者以及被调用者如何实现。它只需知道存在一个具有特定原型和限制条件的被调用函数。简而言之,回调函数就是允许用户把需要调用的方法的指针作为参数传递给一个函数,以便该函数在处理相似事件的时候可以灵活的使用不同的方法。

3、回调函数常见应用场景
不同模块由不同开发人员实现,为了实现模块间信息交互触发行为。(似乎很难理解,下面看模型吧)

3、函数注册和回调的模型

模块A用来实现出现各种事件后的函数处理,程序B 用来监控发生的事件。A模块向B模块注册函数,B模块监控到事件后回调事件的函数处理。

//test.h  头文件
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <sys/types.h>
typedef void (*pf_callbakck)(int a);

typedef struct Compute_ST
{
	int index;
	pf_callbakck function;
}Compute_ST;

int Registe_Callback_Fun(Compute_ST *registed_fun);

void mgmtb_fun(int num);

/A Module/
/TestA.c 文件
实现回调函数
/
#include “test.h”

void callback_fun(int event)
{
switch(event)
{
case 1:
{
printf(“ABCDEFG.\n”);

		}
		break;
	case 2:
		{
			printf("abcdefg.\n");
		}
		break;
	case 3:
		{
			printf("1234567.\n");
		}
		break;
	case 4:
		{
			printf("7654321.\n");
		}
		break;
	default:
		{
			printf("New event, %d.\n",event);
		}
}

}

void main()
{

	int event = 0;
	Compute_ST ptr_compute;
	
	ptr_compute.index = 1;
	ptr_compute.function = callback_fun;
	//注册回调函数
	if(-1 == Registe_Callback_Fun(&ptr_compute))
	{
		printf("Registe failed.\n");
	}
	
	for(;;)
	{
		printf("Enter number:");
		scanf("%d", &event);
		
		if(event == 0)
		{
			return;
		}
		//触发事件
		mgmtb_fun(event);
	}
	return;
}
/*B Module
testB.c文件
实现注册函数
实现事件触发回调*/
#include "test.h"

pf_callbakck g_ptrfun;

int Registe_Callback_Fun(Compute_ST *registed_fun)
{
	if(1 != registed_fun->index)
	{
		printf("Registe failed.\n");
		return -1;
	} 
	g_ptrfun = registed_fun->function;
}

void mgmtb_fun(int event)
{
	g_ptrfun(event);
}

把上面三个文件放在同一个目下编译

[root@localhost home]# gcc testA.c testB.c -o test.exe
[root@localhost home]# ./test.exe
Enter number:3
1234567.
Enter number:2
abcdefg.
Enter number:1
ABCDEFG.
  • 14
    点赞
  • 55
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值