Home > Blockchain >  Portable way to print function pointers?
Portable way to print function pointers?

Time:02-27

I am wondering if this is a portable way to print function pointers.
Casting the function pointer directly to unsigned char * is non-portable.

/* writehex() prints the given byte as its hex representation to the given FILE * */
extern void writehex(FILE *, const unsigned char);

/* Theoretical printf() implementation. */
int printf(const char *format, ...) {

    ...

    void (*fptr)(void);
    const unsigned char *bytes = (const unsigned char *) &fptr;
    size_t i;

    fptr = va_arg(ap, ((void)(*)(void)));
    for (i = 0; i < sizeof(fptr);   i)
        writehex(stdout, *bytes  );

    ...
}

CodePudding user response:

Casting a function pointer to void * or other pointer to objects may lose information as the function pointer may be wider.

There is no great way to portably print function pointers - a shortcoming of C.

Alternatives:

Convert to a wide integer

Try the widest.

if (sizeof function_pointer <= sizeof(uintmax_t)) {
  printf("0x%jX\n", (uintmax_t) function_pointer);
}

Memory dump (OP's approach)

Note that padding and endian issues are in play. Output may include additional junk and unexcepted order, yet this will always "work" in that it is portable and compliant.

"Casting the function pointer directly to unsigned char * is non-portable." does not apply here as it is OK to cast the address of a function pointer to a void *

else {
  unsigned char buf[sizeof(function_pointer)];
  memcpy(buf, &function_pointer, sizeof buf);
  printf("0x");
  for (unsigned i=0; i<sizeof buf; i  ) {
    printf("X", buf[i]);
  }
  printf("\n");
}

  printf("0x");
  for (unsigned i = 0; i

  printf("0x%jX\n", (uintmax_t) function_pointer);
}
  

Consider the wider variety of architectures, the text output from printing function pointers has very different interpretations across implementations.

  • Related