簡體   English   中英

C ++函數指針數組:使用char賦值函數

[英]C++ Array of function pointers: assign function using char

我有一個像這樣的函數指針數組:

void (*aCallback[10])( void *pPointer );

我正在為這個數組分配函數:

aCallback[0] = func_run;
aCallback[1] = func_go;
aCallback[2] = func_fly;

“run”,“go”,“fly”等名稱存儲在另一個數組中。 是否可以使用char將函數分配給函數數組? 就像是:

char sCallbackName[64];
sprintf(sCallbackName, "func_%s", "run");
aCallback[0] = sCallbackName; //caCallback[0] = "func_run"; doesn't work of course

感謝幫助。

不直接,沒有。 符號表和其他元信息通常在運行時不可用,C ++是一種編譯語言。

解決它的典型方法是使用一些宏觀技巧,或許沿着這樣:

/* Define a struct literal containing the string version of the n parameter,
 * together with a pointer to a symbol built by concatenating "func_" and the
 * n parameter.
 *
 * So DEFINE_CALLBACK(run) will generate the code { "run", func_run }
*/
#define DEFINE_CALLBACK(n) { #n, func_##n }

const struct
{
  const char* name;
  void (*function)(void *ptr);
} aCallback[] = {
  DEFINE_CALLBACK(run),
  DEFINE_CALLBACK(go),
  DEFINE_CALLBACK(fly)
};

上面的代碼尚未編譯,但至少應該是關閉的。

更新:我在宏旁邊添加了一個注釋來解釋它。 ###運算符是半模糊的,但完全標准,眾所周知,它們的使用總是在這樣的情況下出現。

這是不可能的。

在運行時,名稱無法訪問這些函數,因為編譯器會將名稱轉換為內存地址。

這在vanilla C ++中是不可能的。

像PHP這樣的腳本語言具有這種功能,因為它們是解釋語言。 使用諸如C之類的語言,它在運行之前編譯代碼,您沒有這樣的功能。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM