我有一个查找表,它链接了我所有的“两个字符命令”,例如AA、AB、SS,按第一个字符的字母顺序排列到其对应的函数地址。
command_list 中的行(即分支)对应于它们的 ASCII 值减去“A”
IE。
command_list[0]
是所有“A”命令
command_list[1]
是所有“B”命令。
此外,第二个字符在“分支”下分配了一个“ Twig ”
例如如果命令 AA 被分配给 Twig 0....
command "AA"
变为 command_list['A' -'A']->twig[0]
变为 command_list[0]->twig[0]
然后我可以调用地址 command_list[0]->twig[0]->leaf_function
我的问题是
- 使用
#define CREATE_TWIG(CHAR_1, CHAR_2) twig_t twig_##CHAR_1##CHAR_2 = {.twig_id = 'CHAR_1', .leaf_function = &command_##CHAR_1##CHAR_2};
我可以创建一根 Twig ,但.twig_id
很困惑,并且始终被分配 (int) 1,而不是CHAR_1
的十进制值。这是为什么? - 如何使用宏自动执行此部分?注意: Twig 的数量可以是一个非负整数,最多 26 个,即 A 到 Z
twig_t * A_twigs[2] = {&twig_AD, &twig_AS};
branch_t A_branch = {.branch_id = 'A', .num_twigs = 2, .twigs = A_twigs};
tree command_list[1] = {&A_branch};
其余代码/typedef/结构
typedef struct{
uint8_t twig_id;
void * leaf_function;
}twig_t;
typedef struct{
uint8_t branch_id;
uint8_t num_twigs;
twig_t **twigs;
}branch_t;
typedef branch_t* tree;
void command_AD(void);
void command_AS(void);
#define CREATE_TWIG(CHAR_1, CHAR_2) twig_t twig_##CHAR_1##CHAR_2 = {.twig_id = 'CHAR_1', .leaf_function = &command_##CHAR_1##CHAR_2};
CREATE_TWIG(A,S)
twig_t twig_AD = {.twig_id = 'D', .leaf_function = &command_AD};
twig_t * A_twigs[2] = {&twig_AD, &twig_AS};
branch_t A_branch = {.branch_id = 'A', .num_twigs = 2, .twigs = A_twigs};
tree command_list[1] = {&A_branch};
最佳答案
把“”去掉吗? CHAR_1 包含您的字符 ascii 值。
关于用于创建查找表的 C 预处理器宏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58919131/