Home > front end >  Use a macro to call a function from a string
Use a macro to call a function from a string

Time:11-16

I have a series of functions that I need to call, and all the calls are of the form:

StartingFunctionName[Thing]Callback(&[Thing]);

Where [Thing] is the same thing each time for example, I have to call

StartingFunctionNameMyFunctionCallback(&MyFunction);

and I'd like to rather do foo(MyFunction); where foo would be the macro.

I was wondering if there was a way to use a macro, so that its input is the string (or something like that) Thing, and the output is the correct line of code.

CodePudding user response:

The answer was to use the ## #define foo(thing) StartingFunctionName##thing(& thing)

CodePudding user response:

If this is your pattern:

StartingFunctionName[Thing]Callback(&[Thing]);

and you want the token 'Thing' replaced, then via function like macro:

#define foo(Thing) \
    StartingFunctionName##Thing##Callback(&Thing)

Example:

foo(exit);

expands to

StartingFunctionNameexitCallback(&exit);
  • Related