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;
}
9
  • 1
    I guess you may need some macros to get function name, like stackoverflow.com/questions/15305310/… Commented Aug 2, 2021 at 2: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... Commented Aug 2, 2021 at 2:41
  • 7
    Out of interest, why do you want to get a function pointer to your own function? Commented Aug 2, 2021 at 2:54
  • 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. Commented Aug 2, 2021 at 3: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? Commented Aug 2, 2021 at 3:35

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.