4

I would like to print, for debugging purposes, the address of the function pointer stored in my std::function. I can guarantee that the std::function is going to point to a c-style function or a lambda. Is there any way to do this?

Otherwise I am going to have to store the function pointer in memory when it is added and modify all the lambdas.

I have attempted to use the answer here https://stackoverflow.com/a/18422878/274249 but it doesn’t seem to work.

Some example code:

std::function<void()> func = commands.front();
void * fp = get_fn_ptr<0>(func);
void * bb = &glBindBuffer;
printf("bb is %x\n", bb); // Outputs 5503dfe0
printf("fp is %x\n", fp); // Should be the same as above, but outputs 4f9680
Community
  • 1
  • 1
ashleysmithgpu
  • 1,867
  • 20
  • 39
  • 1
    the `target<>()` member doesn't work for you? – Nim Mar 04 '15 at 11:30
  • I wondered about that, but it always seems to return null: "typedef void (*glBindBufferfp)(GLenum target, GLuint buffer); void * adsf = func.target();" Note I am using visual studio. – ashleysmithgpu Mar 04 '15 at 11:43

1 Answers1

6

Your version doesn't work because the answer you linked to is providing a wrapper around functions to provide a free-standing version you can use regardless of whether the source was a functor, function pointer or std::function.

In your case, you can use the target function of std::function:

void foo(){}

std::function<void()> f = foo;
auto fp = *f.target<void(*)()>();
auto bb = &foo;
printf("bb is %x\n", bb);
printf("fp is %x\n", fp);

Output:

bb is 80487e0
fp is 80487e0
TartanLlama
  • 63,752
  • 13
  • 157
  • 193
  • that does work, but I am using std::bind(glBindBuffers, x, y) and target() seems to return null to whatever I pass it: typedef void(*glBindBufferfp)(GLenum target, GLuint buffer); std::function f = std::bind(glBindBuffer, 1, 1); auto fp = *f.target(); auto bb = &glBindBuffer; – ashleysmithgpu Mar 04 '15 at 11:57
  • Unfortunately the type of `std::bind` is unspecified and won't convert to a function pointer for you to print out. – TartanLlama Mar 04 '15 at 12:04
  • I see, so I will have to modify things to pass in the function pointer at the source. Thanks – ashleysmithgpu Mar 04 '15 at 12:06
  • I'm confused by all the answers to this question. What is void(*)() and how is it related to void()? My problem involves a function with a return type and parameters and I don't know how to apply this solution to my problem. – Willy Goat Mar 08 '17 at 20:52
  • @WillyGoat `void()` is the type of a function taking no arguments and returning nothing, `void(*)()` is a pointer to such a function. – TartanLlama Mar 09 '17 at 08:25