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?
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 ()>;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With