我不确定这是你想要的,但你可以这样做。声明一个结构来保存函数名称和地址,以及文件范围内的函数数组:
#define FNUM 3
struct fnc {
void *addr;
char name[32];
};
void (*f[FNUM])();
struct fnc fnames[FNUM];
在你的代码中通过函数名手动初始化这些,例如
fnames[0] = (struct fnc){foo1, "foo1"}; // function address + its name
fnames[1] = (struct fnc){foo2, "foo2"};
fnames[2] = (struct fnc){foo3, "foo3"};
创建一个函数来搜索数组,例如
char *getfname(void *p)
{
for (int i = 0; i < FNUM; i++) {
if (fnames[i].addr == p)
return fnames[i].name;
}
return NULL;
}
我对此进行了快速测试。我在main 中初始化了数组,并调用了foo1()。这是我的函数和输出:
void foo1(void)
{
printf("The pointer of the current function is %p\n", getfnp(__func__));
printf("The name of this function is %s\n", getfname(getfnp(__func__)));
printf("The name of the function at pointer f[2] (%p) is '%s'\n", f[2],
getfname(f[2]));
}
The pointer of the current function is 0x400715
The name of this function is foo1
The name of the function at pointer f[2] (0x40078c) is 'foo3'
或者,更一般地说:
void foo2(void)
{
for (int i = 0; i < FNUM; i++) {
printf("Function f[%d] is called '%s'\n", i, getfname(f[i]));
}
}
Function f[0] is called 'foo1'
Function f[1] is called 'foo2'
Function f[2] is called 'foo3'