![]() |
|
Implementing a basic jump table for dynamic command parsing - Printable Version +- Sinisterly (https://sinister.ly) +-- Forum: Coding (https://sinister.ly/Forum-Coding) +--- Forum: C, C++, & Obj-C (https://sinister.ly/Forum-C-C-Obj-C) +--- Thread: Implementing a basic jump table for dynamic command parsing (/Thread-Implementing-a-basic-jump-table-for-dynamic-command-parsing) |
Implementing a basic jump table for dynamic command parsing - phyrrus9 - 04-17-2018 So, was in a PM with another member who was complaining about having to have a massive command parser with a shitload of if-strncmp's in it. I gave him this C code to solve that problem and be more clean, maybe you guys will like it as well: Code: #define ALLOWED_COMMANDS 2
void helpfunc(void)
{
printf("help message\n");
}
void clearfunc(void)
{
// some clear function
}
struct jmp_tbl_s
{
const char *command;
void (*handler)(void);
} jump_table[ALLOWED_COMMANDS] =
{
(struct jmp_tbl_s)
{
.command = "help",
.handler = &helpfunc
},
(struct jmp_tbl_s)
{
.command = "clear",
.handler = &clearfunc
}
};
void processCommand(const char *command)
{
int i;
size_t cmdlen;
const size_t len = strlen(command);
for (i = 0; i < ALLOWED_COMMANDS; ++i)
{
cmdlen = strlen(jump_table[i].command);
if (!strncpy(jump_table[i].command, command, len > cmdlen ? cmdlen : len))
{
*(jump_table[i].handler)();
break;
}
}
}RE: Implementing a basic jump table for dynamic command parsing - drxddock - 04-19-2018 Great code! Easily editable and works great. But what about if the functions needed arguments based on user input? RE: Implementing a basic jump table for dynamic command parsing - phyrrus9 - 04-19-2018 (04-19-2018, 04:17 PM)0xAeschylus Wrote: Great code! Easily editable and works great. But what about if the functions needed arguments based on user input? There's 2 ways of attacking that: Option 1 is to pass the c-string of the command to every function called, and then have a va_list on each of the prototypes, allowing each function to read the rest of the arglist (or parse it ahead of time). Option 2 is to parse out the arglist based on the command inside that if statement and let every function have a different number of args. To do this, simply remove the void from the proto in the struct, and then C won't enforce the argument list checks and you can pass as many or as few as you need. I'd advise option 2, then add a "group" field to make it easier |