3

In Windows/MSVS/C++ I can get a function pointer by pointing to its name like this:

void foo()
{
    auto fooPtr = &foo;
}

But can I do the same thing without knowing the name of the function?

void foo()
{
    auto fnPtr = &thisFunction; //no
}

Use case: I want to define a macro I can put at the top of many functions which will declare a pointer to the function. Ex:

#define defFnPtr auto fnPtr = &thisFunction
void foo()
{
    defFnPtr;
}
void bar()
{
    defFnPtr;
}
Tyson
  • 1,226
  • 1
  • 10
  • 33
  • 1
    I guess you may need some macros to get function name, like https://stackoverflow.com/questions/15305310/predefined-macros-for-function-name-func – fas Aug 02 '21 at 02:36
  • 2
    Getting the function name is easy, yes, but I don't see a way to destringify the name to a variable. Ex: "auto fnPtr = &(\_\_FUNCTION\_\_);" wouldn't work... – Tyson Aug 02 '21 at 02:41
  • 7
    Out of interest, why do you want to get a function pointer to your own function? – Fantastic Mr Fox Aug 02 '21 at 02:54
  • You want to get a pointer to to the current function without using the function's name. Your "use case" is that you want to get a pointer named `fnPtr` to to the current function, or in other words, a pointer to to the current function without using the function's name. Umm... same thing? Do you have a use case for your use case? – JaMiT Aug 02 '21 at 03:20
  • @JaMiT Look again at my use case...I want the same macro to work in multiple, independent functions. That's why I can't use the explicit function name, because there isn't just one function. – Tyson Aug 02 '21 at 03:28
  • 1
    @FantasticMrFox I want to log the memory address of the current function (not its name as a string...the actual location in loaded memory). I guess I could use GetProcAddress(module, \_\_FUNCTION\_\_) and export all my functions so that their names are all searchable within the module, but that's messy and I don't particularly want to export all my functions. – Tyson Aug 02 '21 at 03:32
  • 1
    @Tyson Look again at what I wrote. I see that your macro cannot use the explicit function name. I am looking at the next step. What is the result of your macro? It produces what you are asking for: a pointer to the current function that can be referred to without using the explicit function name. What is the use case for defining `fnPtr` at the top of many functions? **What is the use case of your use case?** – JaMiT Aug 02 '21 at 03:35
  • @JaMiT see my comment to FantasticMrFox – Tyson Aug 02 '21 at 03:36
  • A non-portable solution is inline assembly. – François Andrieux Aug 02 '21 at 11:26

1 Answers1

2

No, there is no way in standard C++ to get a pointer to the "current" function.

Best that you could do is perhaps to use meta programming: Write a program that generates the line auto fnPtr = &foo; into the source.

That said, I don't think that the goal is worth the effort.

eerorika
  • 232,697
  • 12
  • 197
  • 326