Question

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));
Was it helpful?

Solution

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.

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top