Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling function pointed by void* pointer

Tags:

c

pointers

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.

like image 827
TSM Avatar asked Sep 19 '13 16:09

TSM


People also ask

Can a void pointer point to a function?

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.

What is void * pointer?

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.

Can we call a function using pointer?

You can use pointers to call functions and to pass functions as arguments to other functions.

What is void * C++?

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


2 Answers

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.

like image 159
Nemanja Boric Avatar answered Sep 30 '22 14:09

Nemanja Boric


If I understood correctly, you're probably looking for this:

typedef struct {
    void (*fn)();
    void (*param)();
} event;


event *E;

E->fn();
E->param();
like image 28
P0W Avatar answered Sep 30 '22 13:09

P0W