reinterpret_cast std::function* 往返于 void* [英] reinterpret_cast std::function* to and from void*
问题描述
当我调用从主可执行文件传递的 std::function 时,我在插件中遇到了段错误,方法是将其地址转换为 void*
.我可以用几行独立的代码重现这个问题:
I'm suffering a segfault in a plugin when I call a std::function in it passed from the main executable, via converting it's address to/from void*
. I can reproduce the problem in a few self-contained lines:
#include <iostream>
#include <functional>
int main()
{
using func_t = std::function<const std::string& ()>;
auto hn_getter = func_t{[]() {
return "Hello";
}};
auto ptr = reinterpret_cast<void*>(&hn_getter);
auto getter = reinterpret_cast<func_t*>(ptr);
std::cout << (*getter)() << std::endl; // Bang!
return EXIT_SUCCESS;
}
即使我正在转换为原始类型,它仍然存在段错误.谁能看出我哪里出错了?
Even though I'm casting to the original type, it's still segfaulting. Can anyone see where I'm going wrong?
推荐答案
你的问题的原因与 cast 无关,是因为函数返回了一个 const string &
.您需要:
The cause of your problem has nothing to do with cast, it's because of the function return a const string &
. You need:
using func_t = std::function<const std::string ()>;
正如评论所暗示的,const
这里没有用,只是:
And as comments suggest, const
here is useless, just:
using func_t = std::function<std::string ()>;
这篇关于reinterpret_cast std::function* 往返于 void*的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!