嵌入式技术
最近在看一些开源项目,大佬的思路还是很值得去学习,今天就简单介绍一下单链表的应用,配合回调函数可以玩出新花样,废话不多说直接看代码!
| 头文件
#include "stdio.h" #include "stdint.h" typedef struct sensor { uint8_t flag; void (*callback)(void); struct sensor* next; }sensor_t; extern sensor_t sensor1; extern sensor_t sensor2; extern sensor_t sensor3; void sensor1_callback(void); void sensor2_callback(void); void sensor3_callback(void); void sensor_init(sensor_t* handle, void(*callback)(void)); void sensor_start(sensor_t* handle); void sensor_handle(void);
| 源码
// 链表头指针 static sensor_t* head_handle = NULL; // 创建对象 sensor_t sensor1; sensor_t sensor2; sensor_t sensor3; // 回调函数 void sensor1_callback(void) { printf("sensor1! "); } void sensor2_callback(void) { printf("sensor2! "); } void sensor3_callback(void) { printf("sensor3! "); } // 传感器初始化 void sensor_init(sensor_t* handle, void(*callback)(void)) { handle->callback = callback; handle->flag = 0x00; sensor_start(handle); } // 传感器开始(往链表添加节点) void sensor_start(sensor_t* handle) { sensor_t* target = head_handle; if(head_handle == NULL) { /* 链表为空 */ head_handle = handle; handle->next = NULL; } else { /* 链表中存在节点,遍历找最后一个节点 */ while(target->next != NULL) { /* 去掉重复节点 */ if(target == handle){ break; } target = target->next; } target->next = handle; handle->next = NULL; } } // 传感器处理(遍历链表) void sensor_handle(void) { sensor_t* target = head_handle; while(target != NULL) { target->callback(); target = target->next; } }
| 运用
int main() { sensor_init(&sensor1,sensor1_callback); sensor_init(&sensor2,sensor2_callback); sensor_init(&sensor3,sensor3_callback); sensor_handle(); while (1) { /* code */ } }
这个写法是理论上只会受限于内存大小,理想状态下可以无限创建对象,通过绑定回调函数,能在一定程度上解决调用耦合的问题!
审核编辑:汤梓红
全部0条评论
快来发表一下你的评论吧 !