tags:

views:

53

answers:

4

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.

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.

+2  A: 

This is generally not possible - see http://c-faq.com/misc/symtab.html.

Ofir
i agree. its not possible in all cases. if its a pointer, then you wont know what it points till run time, and at run time compiler omits names.
none
I tried to print this in GDB, and it gave me the correct name. so isn't it should be possible via printf too??
rajneesh
GDB has access to more information than your program has access to - the listing/debug information.
Ofir
so indirectly also i can't get the name of function in printf or fprintf??
rajneesh
A: 

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.

Shay Erlichmen
A: 

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

Eyal
A: 

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)
pmg