一般应用程序直接调用系统、库、底层模块的API;如果反过来,用户写一个函数,让系统直接调用该函数,称为回调。
应用层app.c
#include<stdio.h>
#include"module.h"
void func1(void)
{
printf("func1...\n");
}
void func2(void)
{
printf("func2...\n");
}
int main(void)
{
runcallback(func1);
runcallback(func2);
return 0;
}
底层模块module.c
void runcallback(void (*fp)(void))
{
fp();
}
module.h
#ifndef __RUNCALLBACK__H
#define __RUNCALLBACK__H
void runcallback(void (*fp)(void));
#endif
底层在合适的时机就会去调用应用程序函数。
回调函数解耦
高层模块使用回调函数,底层模块在合适的时机就会去调用高层模块的函数,达到模块间双向通信的目的,但同时又引入了耦合。解耦的方法是在两个模块间定义个抽象接口。
app.c
#include <stdio.h>
#include "module.h"
int sd_read(void)
{
printf("sd read fun\n");
return 90;
}
struct storage_device sd={
"sdcard",sd_read
};
void main()
{
register_device(sd);
read_dev("sdcard");
}
module.c
#include <stdio.h>
#include "module.h"
#define MAX_DEV 100
struct storage_device dev_list[MAX_DEV]={0};
int num=0;
int register_device(struct storage_device dev)
{
if(num<MAX_DEV)
dev_list[num++]=dev;
return 0;
}
int read_dev(char *dev_name)
{
int i;
for(i=0;i<MAX_DEV;i++)
{
if(!strcmp(dev_name,dev_list[i].name))
break;
}
if(i==MAX_DEV)
{
printf("err\n");
return -1;
}
return dev_list[i].read();
}
module.h
#ifndef _MODULE_H_
#define _MODULE_H_
typedef int (*read_fp)(void);
struct storage_device{
char name[20];
read_fp read;
};
extern int read_dev(char *dev_name);
extern int register_device(struct storage_device dev);
#endif