为什么需要回调函数?

       假设A模块是需要调用B模块,而B模块又需要调用A模块,我们知道,模块之间的调用需要包含头文件,那模块的相互调用就存在头文件的相互包含,结果,你自己试试就知道了。不相互包含又不行,下面我们给出行不通的方式(我用main.c来模拟A模块,用test.c来模拟B模块):

main.c内容如下:

#include <stdio.h>
#include "test.h"

void print();

int main()
{
	fun();
	return 0;
}

void print()
{
	printf("hello world\n");
}


test.c内容如下:

#include <stdio.h>
#include "test.h"

void fun()
{
	printf("test\n");
	print();
}


test.h内容如下:

void fun();


      编译不过,因为在test.c中,print函数式不可见的。下面,我们来采用回调函数实现吧(本质是主动把函数地址传过去得意得意得意):

main.c的内容如

#include <stdio.h>
#include "test.h"

void callBackPrint();

int main()
{
	fun(callBackPrint);
	return 0;
}

void callBackPrint()
{
	printf("hello world\n");
}


test.c的内容如下:

#include <stdio.h>
#include "test.h"

void fun(void (*p)())
{
	printf("test\n");
	(*p)();
}


test.h的内容如下:

void fun(void (*p)());


     可以正确编译运行,现在,懂了回调函数的作用了吧?如此美妙,妙哉妙哉。如果你开发经验非常丰富,你会发现,回调机制无处不在。

 

    总结一下: 先注册(把函数地址传过去), 后回调(根据传过来的函数地址, 调用函数)。

评论 8
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值