Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pointer to current function

Is there any way to get a pointer to the current function, maybe through gcc extensions or some other trickery?

Edit I'm curious whether it is possible to get the function pointer without ever explicitly using the function's name. I thought I had a good reason for wanting this, realized that I didn't really, but am still curious if it is possible.

like image 538
pythonic metaphor Avatar asked Jun 15 '10 20:06

pythonic metaphor


People also ask

How do you use a pointer to a function?

You can use a trailing return type in the declaration or definition of a pointer to a function. For example: auto(*fp)()->int; In this example, fp is a pointer to a function that returns int .

Can a pointer point to a function C++?

Passing Pointers to Functions in C++C++ allows you to pass a pointer to a function. To do so, simply declare the function parameter as a pointer type.

What is function pointer explain with example?

Function Pointer Syntax void (*foo)( int ); In this example, foo is a pointer to a function taking one argument, an integer, and that returns void. It's as if you're declaring a function called "*foo", which takes an int and returns void; now, if *foo is a function, then foo must be a pointer to a function.


1 Answers

This isn't especially portable, but should work on at least some platforms (i.e., Linux and OSX, where I can check the documentation; it definitely doesn't work on Windows which lacks the API):

#include <dlfcn.h>

// ...
void *handle = dlopen(NULL, RTLD_LAZY);
void *thisfunction = handle ? dlsym(handle, __FUNCTION__) : NULL;
if (handle) dlclose(handle); // remember to close!

There are a number of other less-portable shortcuts that work on some platforms but not others. This is also not fast; cache it (e.g., in a local static variable) if you need speed.

like image 130
Donal Fellows Avatar answered Oct 20 '22 01:10

Donal Fellows