Print the name of function assigned to a function pointer
I need to print the name of functions which is already stored in a function pointer.
Eg.
preValidateScriptHookFunc = (srvScrGenFuncPtrType)SRV_VerifyPymtOrderMaintDtls_validate_data;
I want the value "SRV_VerifyPymtOrderMaintDtls_validate_data" as output during program run via preValidateScriptHookFunc.开发者_StackOverflow中文版
preValidateScriptHookFunc is a function pointer which can store any function name. Please let me know which format specifier should be used in printf or fprintf.
This is generally not possible - see http://c-faq.com/misc/symtab.html.
I'm afraid that without using debug info api (which depends on the platform your in) or using some kind clever trickery with register the pointer in a lookup table it is just not possible.
Depending on your compiler, you might be able to use a pre-defined macro.
http://msdn.microsoft.com/en-us/library/b0084kay(VS.71).aspx
As Ofir says in his answer, you basically cannot do that. The names of the functions only exist before linking is done (they may endure afterwards in debugging data). After link it's only pointers.
If you're willing to store the function addresses somewhere and compare to them, you can do somewhat like this:
$ cat 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)
精彩评论