reinterpret_cast std::function* to and from void*

半腔热情 提交于 2019-12-10 14:16:40

问题


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?


回答1:


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

And as comments suggest, const here is useless, just:

using func_t = std::function<std::string ()>;


来源:https://stackoverflow.com/questions/49303730/reinterpret-cast-stdfunction-to-and-from-void

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!