开发者

Calling a Function from a String in C

In C, how to do you call a function from just having its name as a string? I have this:

int main(int argc, const char *argv[])
{
    char* events[] = {
        "test",
        "test2"
    };

    int i = 0;
    for (; i &l开发者_如何转开发t; 2; ++i){
        char* event = events[i];
        // call function with name of "event"
    }
    return 0;
}


You can do it, but there's not much built-in to help out.

typedef struct { 
    char *event_name;
    void (*handler)();
} event_handler;

then search through an array (or whatever) of event_handlers, and when you find the right name, call the associated function.


There is no standard way to do this. In practice you can sometimes do it using platform specific things (such as dlopen on *nix), but it's just not a very good idea. If you really want to do something like this, you should be using a reflective language.

Set up a table of structs of strings and function pointers to use as a lookup for your function.


If you want to call a function that was linked in using the dynamic linker (or if your program was compiled with -rdynamic) you can use dlsym() to get the address of a function pointer and call that.

If you'd like to invoke a function based on the contents of a given string, you can use the above, or you can wrap a constant string with a function pointer inside of a structure and invoke each.


Compare the input string against known function names.

If string X... call function X


since your array only has 2 items... my noob way =)

if ( strcmp(event, "function1") == 0 ) {
  function1();
} else if { strcmp(event, "function2") == 0 ) {
  function2();
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜