There is no way to directly call a function by string like you want in the standard C library. If it were C++, you could create a std::map
of string
to function pointer, but not in C. You'll probably have to resort to a series of strcmp
s if C++ is not an option.
/* These are your handler functions */
void user_fn() { printf("USER fn\n"); }
void pass_fn() { printf("PASS fn\n"); }
/* Stores a C string together with a function pointer */
typedef struct fn_table_entry {
char *name;
void (*fn)();
} fn_table_entry_t;
/* These are the functions to call for each command */
fn_table_entry_t fn_table[] = {{"USER", user_fn}, {"PASS", pass_fn}};
/* fn_lookup is a function that returns the pointer to the function for the given name.
Returns NULL if the function is not found or if the name is NULL. */
void (*fn_lookup(const char *fn_name))() {
int i;
if (!fn_name) {
return NULL;
}
for (i = 0; i < sizeof(fn_table)/sizeof(fn_table[0]); ++i) {
if (!strcmp(fn_name, fn_table[i].name)) {
return fn_table[i].fn;
}
}
return NULL;
}
int main() {
fn_lookup("USER")();
fn_lookup("PASS")();
}