Calling a Function from a String in C

≡放荡痞女 提交于 2021-02-17 02:44:05

问题


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 < 2; ++i){
        char* event = events[i];
        // call function with name of "event"
    }
    return 0;
}

回答1:


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.




回答2:


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.




回答3:


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.




回答4:


Compare the input string against known function names.

If string X... call function X




回答5:


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

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


来源:https://stackoverflow.com/questions/5875705/calling-a-function-from-a-string-in-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!