I have an issue. I'm trying to convert a void* to std::function. This is just a simple example, any suggestions will be appreciated
#.h file
class Example {
public:
  Example();
  int foo(void* hi);
  int fooFunc(std::function<int(int, int)> const& arg, int x, int y) {
    foo(arg.target<void*>(), x, y);
    return 2;
  }
};
#.cpp file
Example::Example() {
  }
  int Example::foo(void * func, int x, int y)
  {
    //cast back to std::function
    func(x, y);
    std::cout << "running in foo: " << a << "\n";
    return a;
  }
Every casting i tried did not work.
I know i can send a std::function in this example, but it's for something bigger and i'm working on an example to make it work here.
The whole meaning of void*, is for sometimes to use it, in these situations, when you don't know what you will receive, and then cast it to the specific usage you need.
Thanks!
You can't.
You can cast a data pointer to void* and then back to the same pointer type you have started with. std::function is not a pointer type, so the cast is statically invalid, and it's not the same thing you have started with. You have started with a .target of type void(*)() but it's not a data pointer, it's a function pointer, so casting it to void* and back is implementation-defined.
You can:
void(*)() anyway. Will work on most (but not all) platforms.void(*)() instead of void* as a universal function pointer (you can cast it to other function types).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