extern C 以及 c语言 函数指针实现 回调函数 (具体实例,清晰)
extern c 结构
出现在 .h 头文件中
因为 c++ 和c引用头文件的机制稍有不同
为了使c++兼容 .h的头文件,使用这个结构
#ifdef __cplusplus //兼容c++ 的头文件定义
extern "C" {
#endif
//
//函数声明
//
#ifdef __cplusplus
}
#endif
函数指针
指向函数的指针
实例
#include "stdio.h"
int Max(int x, int y){
if (x > y) //如果 x > y, 返回 x
return x;
return y; //否则, 返回 y
}
int main(void)
{
int (*index)(int ,int)=Max;
printf("%d" ,index(3,4));
return 0;
}
回调函数
其实两者一致,都是用函数指针来调用函数
回调定义
这里举我最近在看的代码实例
先解释一下这里的回调函数是,按键状态的回调函数,共有7种状态,可以设置7种回调函数。
typedef void (*BtnCallback)(void*); //定义 回调函数的类型
typedef enum {
PRESS_DOWN = 0,
PRESS_UP,
PRESS_REPEAT,
SINGLE_CLICK,
DOUBLE_CLICK,
LONG_RRESS_START,
LONG_PRESS_HOLD,
number_of_event, //7
NONE_PRESS
}PressEvent; //定义7种状态
typedef struct Button {
//我只留下了 回调函数
BtnCallback cb[number_of_event];
//7种事件状态的回调函数 这里其实也就是一个 7个 函数指针的数组
// 等价于 (*cb[number_of_event])(void*)
}Button;
回调实现
// 真正的 按键 被按下事件的 回调函数
void key2_PRESS_DOWN_Handler(void* btn)
{
printf("key2_PRESS_DOWN!\n");
}
//将 被按下事件的函数指针 指向 该回调函数
button_attach(&key3, PRESS_DOWN, key3_PRESS_DOWN_Handler);
void button_attach(struct Button* handle, PressEvent event, BtnCallback cb)
{
handle->cb[event] = cb;
}
// 这里调用回调函数
#define EVENT_CB(ev) if(handle->cb[ev])handle->cb[ev]((Button*)handle)
void button_handler(struct Button* handle)
{
EVENT_CB(PRESS_DOWN);
}
/*等价于
void button_handler(struct Button* handle)
{
if(handle->cb[PRESS_DOWN])
printf("key2_PRESS_DOWN!\n");
}
*/
初看较为复杂,理解了就简单了,这种结构感觉可以让程序更系统一些,算是更规范吧。