Login Register


Implementing a basic jump table for dynamic command parsing filter_list
Author
Message
Implementing a basic jump table for dynamic command parsing #1
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;        }    } }

Reply

RE: Implementing a basic jump table for dynamic command parsing #2
Great code! Easily editable and works great. But what about if the functions needed arguments based on user input?

Reply

RE: Implementing a basic jump table for dynamic command parsing #3
(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

Reply







Users browsing this thread: 1 Guest(s)