I have an event struct that looks like this
typedef struct {
void* fn;
void* param;
} event;
How can I call this function by pointer as part of the struct. For example, these do not work:
event->(*function)();
event->function();
(*event->function)();
I want to know how to make the function call both with and without using the additional void* param. I was originally using this link as a reference:
http://www.cprogramming.com/tutorial/function-pointers.html
I've used these function pointers before, but have trouble getting the syntax correct.
A pointer to void means a generic pointer that can point to any data type. We can assign the address of any data type to the void pointer, and a void pointer can be assigned to any type of the pointer without performing any explicit typecasting.
The void pointer in C is a pointer that is not associated with any data types. It points to some data location in the storage. This means that it points to the address of variables. It is also called the general purpose pointer. In C, malloc() and calloc() functions return void * or generic pointers.
You can use pointers to call functions and to pass functions as arguments to other functions.
When used as a function return type, the void keyword specifies that the function doesn't return a value. When used for a function's parameter list, void specifies that the function takes no parameters. When used in the declaration of a pointer, void specifies that the pointer is "universal."
You need to cast void*
pointer to the function pointer first:
#include <stdio.h>
typedef struct {
void* fn;
void* param;
} event;
void print()
{
printf("Hello\n");
}
int main()
{
event e;
e.fn = print;
((void(*)())e.fn)();
return 0;
}
Of course, if this is really what you want. If you want your struct to contain pointer to the function, instead of void*
pointer, use the proper type at the declaration:
typedef struct {
void (*fn)();
void* param;
} event;
Here you have fn
declared as a pointer to the void
function, and the param
as void*
pointer.
If I understood correctly, you're probably looking for this:
typedef struct {
void (*fn)();
void (*param)();
} event;
event *E;
E->fn();
E->param();
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