views:

75

answers:

2

Is there any way to unstringify strings provided as macro arguments? I need to be able to call functions who's names are in strings. Something like this:

void hello() {
    printf("Hello, world!");
}

call_func("hello");

How would I implement call_func. It would be in a module that would be #included and would be used to call functions in the main c file. If there is another way to do this where the name wouldn't have to be in strings but could be passed as an argument to a function that would be ok to. This is what I mean:

#define call_func(X) X()
void do_something(Some_kind_of_C_func_type i) {
    call_func(i)
}
void hello() {
    printf("Hello, world!");
}

do_something(C_FUNC(hello));
+1  A: 

Okay, I see two ways to do this, depending on what your goals are.

First are function pointers; essentially treats a function as a variable. See here for a quick overview.

Alternatively, you could build the code you wanted to call in that fashion as a shared library, then use something like dlopen() or LoadLibrary() to open the library, followed by using either interface to access variables / functions.

cubic1271
Function pointers are just what I wanted! Thanks.
None
A: 

Although it's not entirely clear what you want to accomplish, you cannot use macros to take a string entered on runtime and resolve the function of the same name.

What you can do is, register all functions in a list (or a slightly more sophisticated datastructure) and call them by their name.

#define INSERT(fn) addfn(#fn, &fn)
void addfn(char const* name, func_t fp);

Where addfn coult take the issued pointer and put it in a dictionary under the entry name.

bitmask
Using [`dlsym()`](http://www.opengroup.org/onlinepubs/9699919799/functions/dlsym.html) on an appropriate handle would work. You'd need to use [`dlopen(0, 0)`](http://www.opengroup.org/onlinepubs/9699919799/functions/dlopen.html) to get the appropriate handle, I believe. But your fundamental point - that you cannot do it simply (whether using macros or any other technique) is valid.
Jonathan Leffler