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

I have an array of function pointers, for example:

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

I assign functions to an array as follows:

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

Names like "run", "go", "fly" are stored in another array. Is it possible to assign functions to a function array using char? Sort of:

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

Thanks for the help.

+3
source share
4 answers

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

A typical way to solve this problem is to use some macro information, possibly in accordance with 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 must be at least closed.

UPDATE: , . # ## , , , .

+4

.

, .

+1

This is not possible in vanilla C ++.

0
source

Scripting languages ​​such as PHP have this object because they are interpreted by the language. With a language such as C that compiles the code before running, you don't have such a tool.

0
source

Source: https://habr.com/ru/post/1793848/


All Articles