cpointersfunction-pointersvoid-pointers

Is there a workaround for typecasting a function pointer to an object pointer in C?


I have a function called 'bench' which accepts a function pointer that returns a void pointer (for generics).

static inline unsigned long bench(void* (*funcPtr)(va_list), ...)

But if I pass it a function that returns anything else, I get this error -

passing argument 1 of 'bench' from incompatible pointer type

So it outright refuses to type cast. But then if I manually type cast it to a void pointer when calling the bench function, I get this error -

ISO C forbids passing argument 1 of 'bench' between function pointer and 'void *'

A workaround I got to know is to use a wrapper function which returns a void pointer, but then I would have to either create a new wrapper function for every individual function I need to pass, which would be very inefficient, and the other way would be to create a wrapper function for every data type that I will use, which is not that inefficient, but it is. Is there a better workaround?


Solution

  • C has no generic pointer-to-function type, like void * is for objects. However, you can convert any pointer-to-function to any other pointer-to-function type. So, to pass the function foo to bench, you can convert it to the parameter type of bench:

    bench((void *(*)(va_list)) foo);
    

    While that will work to convert and pass the pointer, calling the function relies on it being called via its proper type (something matching its declaration according to the rules for function calls). If foo is not defined in a way compatible with the way that bench calls the function, you will need a wrapper function.