1

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;
}

5 Answers 5

5

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Could you elaborate a little more, I'm not exactly sure how this would be done.
4

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.

Comments

1

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.

2 Comments

I was bored and wrote it: codepad.org/3BRapq7T (unfortunately codepad doesn't seem to offer the library needed)
@Martin: dlopen() and family have been around before: Unix adopted them and POSIX standardized them. A similar facility exists on a couple of non-POSIX systems, like Win32, using LoadLibrary and GetProcAddress.
0

Compare the input string against known function names.

If string X... call function X

Comments

0

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

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

3 Comments

Strings in C don't compare like that.
The straightforward way to compare strings in C is with strcmp(): if (strcmp(event, "function1") == 0) { function1(); }
Just a btw, strcmp return 0 when the strings match, not the other way.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.