Suppose I have a function like below:
void fun(void* p){
SomeType* p = reinterpret_cast<SomeType*>(p);
...
}
The signature is require by the api. I just wonder can I just write it as.
void fun(SomeType* p){
...
}
And cast it to void (*)(void*)
.
While you can cast function pointers to other function pointers and back, calling a function through a pointer that doesn't match its signature is undefined behavior. You cannot just cast it and pass to an API.
In C and C++03, you'd have to create a named wrapper function that matches the signature and preforms the cast. In C++11 and beyond, you can just use a capture-less lambda instead (properly cast):
void fun(SomeType* p){
...
}
int main() {
api_call(+[](void *v) {
fun(static_cast<SomeType*>(v));
});
}
The +
in front of the lambda causes it to be converted into a regular function pointer so long as it's not capturing. It's not strictly needed, but it makes the intent more explicit IMO, without too much verbosity.
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