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?
Void functions are created and used just like value-returning functions except they do not return a value after the function executes. In lieu of a data type, void functions use the keyword "void." A void function performs a task, and then control returns back to the caller--but, it does not return a value.
Void functions, also called nonvalue-returning functions, are used just like value-returning functions except void return types do not return a value when the function is executed. The void function accomplishes its task and then returns control to the caller. The void function call is a stand-alone statement.
Function Pointer Syntaxvoid (*foo)( int ); In this example, foo is a pointer to a function taking one argument, an integer, and that returns void. It's as if you're declaring a function called "*foo", which takes an int and returns void; now, if *foo is a function, then foo must be a pointer to a function.
A void pointer in C++ is a special pointer that can point to objects of any data type. In other words, a void pointer is a general purpose pointer that can store the address of any data type, and it can be typecasted to any type. A void pointer is not associated with any particular data type.
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).
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