繁体   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