jay.lee jay.lee - 25 days ago 10x
C Question

Call a void* as a function without declaring a function pointer

I've searched but couldn't find any results (my terminology may be off) so forgive me if this has been asked before.

I was wondering if there is an easy way to call a

as a function in C without first declaring a function pointer and then assigning the function pointer the address;

ie. assuming the function to be called is type

void *ptr;
ptr = <some address>;
((void*())ptr)(); /* call ptr as function here */

with the above code, I get error C2066: cast to function type is illegal in VC2008

If this is possible, how would the syntax differ for functions with return types and multiple parameters?


Your cast should be:

((void (*)(void)) ptr)();

In general, this can be made simpler by creating a typedef for the function pointer type:

typedef void (*func_type)(void);
((func_type) ptr)();

I should, however, point out that casting an ordinary pointer (pointer to object) to or from a function pointer is not strictly legal (although it is a common extension).