问题
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:
- Ignore the issue and cast to
void(*)()
anyway. Will work on most (but not all) platforms. - Use
void(*)()
instead ofvoid*
as a universal function pointer (you can cast it to other function types). - Use whatever tools C++ offers to avoid the cast altogether.
来源:https://stackoverflow.com/questions/42328816/casting-void-to-stdfunction