Obviously, everything can't be called add_module -- but the other bad side of this is I think you think there's something dynamic going on here. But there isn't: all we're doing is initializing an array. An example I haven't tested, so even though I'm being easy on myself there's going to be four errors in it:
Code:
void hello_world(void *dummy_arg) {
printf("Hello world!\n");
}
void read_int(void *int_var) {
printf("I need an integer: ");
scanf("%d", int_var);
}
void print_linked_list(void *head) {
Node *item = head;
while (item != NULL) {
printf("%d\n", item->data);
item = item->next;
}
}
struct fn_entry {
char *fn_name;
void (*fn_ptr)(void *);
}
#define FUNCTION(x) { #x, x }
struct fn_entry function_list[] = {
FUNCTION(hello_world),
FUNCTION(read_int),
FUNCTION(print_linked_list)
};
In my example, each of my functions knows what to do with the info it has (which is a simple pointer in each case), so I didn't need the handler part -- if some of your functions needed two ints, or three ints and a double, or whatever, you'd need that to turn the function list you provide into a void * to go into the actual function itself.
The FUNCTION is just a macro: so FUNCTION(hello_world) is replaced by the preprocessor with { "hello_world", hello_world } -- a char * (actually a const char *) and a function pointer, which means it initializes one struct in my array of structs.