casting void* to std::function

陌路散爱 提交于 2019-12-24 11:15:35

问题


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!


回答1:


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:

  1. Ignore the issue and cast to void(*)() anyway. Will work on most (but not all) platforms.
  2. Use void(*)() instead of void* as a universal function pointer (you can cast it to other function types).
  3. Use whatever tools C++ offers to avoid the cast altogether.


来源:https://stackoverflow.com/questions/42328816/casting-void-to-stdfunction

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