开发者

call a function by "string"

I wonde开发者_StackOverflowr if it's possible to do something like:

 call("MyFunction");

and have it call a function named MyFunction not having call implement a long switch or if statement.

there probly is some other way to do this, what I really want to achive is to implement the IRC protocol, which get messages, and based on those I want to call the apropiate function

I'm new to C and best practices how things are done so please enlighten me!


Not without defining a table of string-to-function mappings and (probably) some kind of argument passing convention, or using dlopen() (which counts as very advanced hackery).


Not out of the box with C. You could have a hash map or dictionary that has the string as a key and a function pointer. You look up in your dictionary using the string key, then call the function pointer.


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 strcmps 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")();
}


You make a table which relates each string to a function pointer. You then look up the string in the table, and invoke the function through the pointer. The classic K&R text includes code something like this.


I am not a C programmer, and personally would do IRC stuff in a dynamic language, but you could do the following:

create a struct with string field and a function pointer, make an array of all your functions with their "string", sorted by the string. On call, do a binary search on the array, by string, and call the function pointer in the found struct.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜