2010-10-13 368 views
2

我需要打印已存储在函数指针中的函数的名称。例如, preValidateScriptHookFunc = (srvScrGenFuncPtrType)SRV_VerifyPymtOrderMaintDtls_validate_data;打印分配给函数指针的函数名称

我想通过preValidateScriptHookFunc在程序运行期间输出值“SRV_VerifyPymtOrderMaintDtls_validate_data”作为输出。

preValidateScriptHookFunc是一个函数指针,它可以存储任何函数名。 请让我知道应在printf或fprintf中使用哪种格式说明符。

+0

可能的重复[如何从C函数的指针获取函数的名称](http://stackoverflow.com/questions/351134/how-to-get-functions-name-from-functions-pointer-in-c) – Mundi 2012-08-25 07:33:04

回答

2

这通常是不可能的 - 见http://c-faq.com/misc/symtab.html

+0

我同意。在任何情况下都不可能。如果它是一个指针,那么在运行时你不会知道它指向什么,并且在运行时,编译器会忽略名称。 – none 2010-10-13 10:15:45

+0

我试图在GDB中打印这个,它给了我正确的名字。所以是不是应该可以通过printf呢? – rajneesh 2010-10-13 10:19:09

+0

GDB可以访问比程序可以访问的信息更多的信息 - 列表/调试信息。 – Ofir 2010-10-13 11:26:52

0

恐怕没有使用调试信息api(这取决于你的平台),或者使用某种巧妙的技巧将指针注册到查找表中,这是不可能的。

0

由于奥菲尔says in his answer,你基本上无法做到这一点。这些函数的名称只在链接完成之前才存在(它们可能会在调试数据之后忍受)。链接后它只是指针。

如果你愿意的地方存放函数地址,并比较它们,你可以做有点像这样:

$猫3922500.c

#include <stdio.h> 

char *fxname(void *fx) { 
    if (fx == fprintf) return "fprintf"; 
    if (fx == gets) return "gets"; 
    if (fx == scanf) return "scanf"; 
    return "(unknown)"; 
} 

int main(void) { 
    void (*fx)(void); 
    fx = gets; printf("name: %s\n", fxname(fx)); 
    fx = putchar; printf("name: %s\n", fxname(fx)); 
    return 0; 
} 

$ GCC 3922500.c

 
3922500.c: In function 'main': 
3922500.c:12: warning: assignment from incompatible pointer type 
3922500.c:13: warning: assignment from incompatible pointer type 
/tmp/ccvg8QvD.o: In function `fxname': 
3922500.c:(.text+0x1d): warning: the `gets' function is dangerous and should not be used. 

$ ./a.out

 
name: gets 
name: (unknown)