Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it safe to cast void (*p)(SomeType*) to void (*p)(void*)

Tags:

c++

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*).

like image 271
W.H Avatar asked Jun 20 '17 10:06

W.H


1 Answers

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.

like image 60
StoryTeller - Unslander Monica Avatar answered Oct 26 '22 23:10

StoryTeller - Unslander Monica