指向当前函数的指针 [英] Pointer to current function

查看:174
本文介绍了指向当前函数的指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有什么方法可以获得指向当前函数的指针,也许可以通过gcc扩展或一些其他欺骗?



编辑 m好奇是否可以在不明确使用函数名的情况下获取函数指针。我认为我有一个很好的理由想要这个,意识到我没有真正的,但如果可能的话,我仍然很好奇。

这不是特别便携的,但应该至少在某些平台上工作(例如,Linux和OSX,我可以检查文档;它绝对不支持缺少API的Windows):

  #include< dlfcn.h> 

// ...
void * handle = dlopen(NULL,RTLD_LAZY);
void * thisfunction = handle? dlsym(handle,__FUNCTION__):NULL;
if(handle)dlclose(handle); //记得关闭!

还有一些其他便携式快捷键可用于某些平台,但不适用于其他平台。这也不是很快;如果您需要速度,请将其缓存(例如,在本地静态变量中)。


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.

解决方案

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.

这篇关于指向当前函数的指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆