Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

reinterpret_cast std::function* to and from 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?

like image 272
cmannett85 Avatar asked Mar 15 '18 15:03

cmannett85


1 Answers

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 ()>;
like image 199
llllllllll Avatar answered Nov 16 '22 18:11

llllllllll