reinterpret_cast std::function* to and from void*

reinterpret_cast std::function* to and from void*

本文关键字:to from void and function cast std reinterpret      更新时间:2023-10-16

当我调用从主可执行文件传递的 std::function 时,我在插件中遇到了段错误,方法是将其地址转换为/从void* . 我可以用几个独立的行重现问题:

#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;
}

即使我正在转换为原始类型,它仍然是段错误。 谁能看出我哪里出了问题?

问题的原因与 cast 无关,这是因为函数返回 a const string & 。你需要:

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

正如评论所暗示的那样,这里的const是没有用的,只是:

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