1

Is it possible to map function pointer to std::string in standard conformant C++?

Casting function pointers to object pointers and even doing pointer arithmetic is off limits with function pointers but in this related question

How to format a function pointer?

the following code is given:

int (*funcptr)() = main;
unsigned char *p = (unsigned char *)&funcptr;
int i;

for (i = 0; i < sizeof funcptr; i++)
{
    printf("%02x ", p[i]);
}
putchar('\n');

That code has withstood peer scrutiny. I'm a bit confused by it. Accessing a function pointer with array syntax is legal but pointer arithmetic is not?

Here's what I have at the moment. My compiler doesn't complain and with a sample size of 1 things seem well behaved.

template<class F>
std::string fptr_to_str(F fptr)
{
    auto fptr_bytes = (const char*)fptr;
    return {fptr_bytes, sizeof(fptr_bytes)};
}
Community
  • 1
  • 1
Praxeolitic
  • 22,455
  • 16
  • 75
  • 126
  • 4
    That first code doesn't *dereference* the function pointer, with or without array syntax, nor does it perform any pointer arithmetic with it. It accesses the memory addressed by the value in `p` with array syntax, which happens to be the *address* of a function pointer. – WhozCraig Mar 12 '15 at 23:25

2 Answers2

5

The alternate code takes the address of the pointer to the function, and extracts bytes there.

Your code takes the address of the function, and extracts bytes there.

These are different operations.

Yakk - Adam Nevraumont
  • 262,606
  • 27
  • 330
  • 524
  • Gotcha. So just to be sure, is `auto fptr_bytes = (const char*)&fptr; return {fptr_bytes, sizeof(fptr)};` doing the right thing? – Praxeolitic Mar 12 '15 at 23:38
  • I would make the template type `T*` to be clear (not really needed unless someone passes `T` explicitly). Then I think that is safe. You can read/copy any pod type as a buffer of char, and string is just a buffer of char at the lowest level. I would use `vector` instead myself, or even `array`, as a matter of style. – Yakk - Adam Nevraumont Mar 12 '15 at 23:48
0

Casting function pointers to object pointers is only naughty if your platform actually has separate code and data segments with different pointer sizes (which virtually nobody does anymore). So although technically it's bad, in reality, nobody cares, and core OS APIs on common platforms like Linux and Windows depend on it.

Just cast to void* and then format that like any other pointer.

Puppy
  • 144,682
  • 38
  • 256
  • 465
  • Except this is C++, where you can also have member function pointers which are sometimes not even a memory address at all. :) – Dark Falcon Mar 12 '15 at 23:26
  • It's not so bad. Casting a function pointer to an object pointer is not UB, just "conditionally supported by the implementation". – sbabbi Mar 13 '15 at 00:21