Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 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?

like image 202
jay.lee Avatar asked Apr 14 '10 07:04

jay.lee


People also ask

What does void * func () mean?

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.

Can you call a void function?

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.

How do you call a void function pointer in C?

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.

What is void * ptr C++?

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.


1 Answers

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

like image 96
jamesdlin Avatar answered Oct 05 '22 19:10

jamesdlin