Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I have an array of function pointers like this:

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
like image 671
Ilyssis Avatar asked Feb 06 '26 08:02

Ilyssis


2 Answers

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.
like image 60
unwind Avatar answered Feb 07 '26 20:02

unwind


That is not possible.

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

like image 41
Tomas Avatar answered Feb 07 '26 22:02

Tomas