开发者

C++ Array of function pointers: assign function using char

开发者 https://www.devze.com 2023-02-12 08:04 出处:网络
I have an array of function pointers like th开发者_如何学Gois: void (*aCallback[10])( void *pPointer );

I have an array of function pointers like th开发者_如何学Gois:

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

I am assigning functions to the array like that:

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

The names like "run", "go", "fly" are stored in another array. Is it possible to assign the functions to the function-array using a char? Something like:

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


Not directly, no. The symbol table and other meta-information is generally not available at runtime, C++ is a compiled language.

The typical way to solve it is to use some macro trickery, perhaps along the lines of this:

/* 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)
};

The above code has not been compiled, but it should be at least close.

UPDATE: I added a comment next to the macro to explain it a bit. The # and ## operators are semi-obscure, but totally standard, well-known, and their use always crops up in cases like these.

  • # is the quoting or stringizing operator.
  • ## is the token concatenation operator.


That is not possible.

The functions are not accessible by name at runtime because the compiler translates a name to a memory address.


This is not possible in vanilla C++.


Scripting languages like PHP has this facility because they are interpreted language. With a language, such as C, which compiles the code prior to running, you don't have such facility.

0

精彩评论

暂无评论...
验证码 换一张
取 消