私はこれがあなたの望むものかどうかはわかりませんが、このようなことをすることができます。関数名とアドレスを保持するための構造、ファイルスコープで関数の配列を宣言:
#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'
http://stackoverflow.com/q/679021/139010 –
@ C++バージョンは、これを行うための標準的な方法はありません。どのコンパイラを使用していますか? –
Cで関数のポインタから関数の名前を取得する方法http://stackoverflow.com/questions/351134/how-to-get-functions-name-from-functions-pointer-in-c – zzk