开发者

C Unstringification with macros

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


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.


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.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜