如何获取存储在 std::function 中的 c 风格函数的地址?

How do I get the address of a c-style function stored in an std::function?

出于调试目的,我想打印存储在 std::function 中的函数指针的地址。我可以保证 std::function 将指向 C 风格的函数或 lambda。有什么办法吗?

否则我将不得不在添加函数指针时将其存储在内存中并修改所有 lambda。

我曾尝试使用这里的答案 但它似乎不起作用。

一些示例代码:

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

你的版本不起作用,因为你链接到的答案是提供一个函数包装器,以提供一个你可以使用的独立版本,无论源是仿函数、函数指针还是 std::function .

在你的情况下,你可以使用std::functiontarget功能:

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

输出:

bb is 80487e0
fp is 80487e0