回调函数

定义

回调函数是对可执行代码的引用,它作为参数传递给其他代码,允许较低级别的软件层调用在较高级别层中定义的函数。

回调允许驱动程序或库嵌入式开发人员在较低层指定行为,但将实现定义留给应用程序层。

三部分组成

1. 回调函数

定义一个回调函数:

1
typedef void (*callback)(void);

2. 回调注册

提供函数调用的另一方在初始化时,需要将回调函数的指针传给调用者:

1
void register_callback(callback Fun);

3. 回调执行

当特定事件发生时,调用者使用回调函数进行事件处理:

1
2
3
if (event == True) {
Fun();
}

回调函数的作用

  1. 恰当时机发送通知:事件触发的异步操作
  2. 程序设计更加灵活
  3. 提高效率
  4. 同步/异步:支持同步和异步两种模式

典型使用

1
2
3
4
5
6
7
8
9
10
11
12
13
typedef void (*ServiceHandler)(uint8_t N_TAType, uint16_t length, uint8_t* MessageData);

typedef struct {
bool support;
uint8_t serviceName;
uint8_t PHYDefaultSession_Security : 4;
uint8_t PHYProgramSeesion_Security : 4;
uint8_t PHYExtendedSession_Security : 4;
uint8_t FUNDefaultSession_Security : 4;
uint8_t FUNProgramSeesion_Security : 4;
uint8_t FUNExtendedSession_Security : 4;
ServiceHandler serviceHandle;
} SessionService;

编写模式

1
2
3
4
5
6
7
8
9
10
11
12
13
14
// 1. 定义回调类型
typedef void (*pFunCallBack)(int);

// 2. 回调登记函数
void transform(int param1, int param2, pFunCallBack pfun) {
for (int i = 0; i < param1; i++) {
pfun(param2);
}
}

// 3. 实现具体回调
void callback_print(int value) {
print(value);
}