Skip to content

240923-C语言自编小模块笔记

1 字符串自编协议

对于字符串协议,一种更好的方法是使用一个映射表(map)或者查找表(lookup table),将字符串命令映射到对应的处理函数。这样可以避免使用多个 strstr 和 if 语句,使代码更加清晰和易于维护。

typedef void (*config_processing_func)(char*);

typedef struct 
{
    const char *command;
    config_processing_func func;
} cmd_map;
  • 函数指针类型,名为 config_processing_func ,没有返回值,形参为字符串指针
  • 结构体,包含需要匹配的 command & 处理函数
static const cmd_map screen_cmd_map[] =
    {
        {"MC+WAN+WIFI=", wifi_config_processing},
        {"MC+WAN+ETH=", eth_config_processing},
        {"MC+TSUM=", tsum_config_processing},
        {"MC+TNUM=", tnum_config_processing},
    };

    static const size_t cmd_map_size = sizeof(screen_cmd_map) / sizeof(screen_cmd_map[0]);

for (size_t i = 0; i < cmd_map_size; i++)
{
    char *temp_ptr = strstr((char const *)temp_buffer_ptr, screen_cmd_map[i].command);
    if (temp_ptr != NULL)
    {
        screen_cmd_map[i].func(temp_ptr);
    }
}

创建一个 cmd_map 类型的数组,其内部每一个成员都是一个 cmd_map 结构体,