我想根据func_name
字符串调用函数。
我的代码如下:
#define MAKE_FUNCNAME func_name##hello
void call_func(void* (*func)(void))
{
func();
}
void *print_hello(void)
{
printf("print_hello called\n");
}
int main(void)
{
char func_name[30] = "print_";
call_func(MAKE_FUNCNAME);
return 0;
}
但是这段代码不起作用。我希望代码像 call_func(print_hello)
一样工作。但是预处理器像 call_func("print_hello")
一样对待我的代码。如何在 C 中使用宏进行异常处理?还是不能使用 C?
最佳答案
然后您的代码的问题是 func_name
的值仅在运行时已知。
但是你可以这样:
#define MAKE_FUNCNAME(FUNCNAME) FUNCNAME##hello
void call_func(void* (*func)(void))
{
func();
}
void *print_hello(void)
{
printf("print_hello called\n");
}
int main(void)
{
call_func(MAKE_FUNCNAME(print_));
return 0;
}
但是不可能像在您的代码片段中那样在宏参数中使用字符串值。
如果你想使用字符串值获取调用函数的名称,你可以使用一个表来存储函数指针,函数名称如下:
struct {
const char *name;
void (*ptr)(void);
};
您可以使用此结构的数组在运行时使用字符串值找出函数指针。这是使用运行时字符串通过名称调用函数的最常见解决方案。
关于c - 如何使用宏来调用函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33462489/