13

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 void* 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(void)

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?

Stargateur
  • 24,473
  • 8
  • 65
  • 91
jay.lee
  • 19,388
  • 8
  • 39
  • 38

3 Answers3

31

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 in standard C (although it is a common extension).

jamesdlin
  • 81,374
  • 13
  • 159
  • 204
13

I get awfully confused when casting to function types. It's easier and more readable to typedef the function pointer type:

void *ptr = ...;
typedef void (*void_f)(void);
((void_f)ptr)();
Marcelo Cantos
  • 181,030
  • 38
  • 327
  • 365
12

In C++: reinterpret_cast< void(*)() > (ptr) ()

The use of reinterpret_cast saves you a set of confusing parentheses, and the < > clearly sets the type apart from the call itself.

MSalters
  • 173,980
  • 10
  • 155
  • 350