Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
707 views
in Technique[技术] by (71.8m points)

c - 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...