简体   繁体   中英

void* function pointer array cast

I have an array which looks like this:

void* functions[]; // pointer to functions, each function returns an int and has int parameters A and B

I would like to cast this into the following:

int (*F)(int a, int b) = ((CAST HERE) functions)[0];
int result = F(a, b);

I have already tried "(int (*)(int, int))" as the cast but the compiler complained I am trying to use the function pointer as an array.

It will help to use a typedef for the function type:

typedef int F_type(int, int);

Then you can write:

F_type *F = (F_type *)(functions[0]);

It would be undefined behaviour (strict aliasing violation) to try and cast functions to something else before using the index operator.

Note that it is not supported by Standard C to convert void * to be function pointers. If possible, make the array be function pointers in the first place:

F_type *functions[] = { &func1, &func2 };

NB. Some people prefer using a typedef for the function pointer type, instead of the function type. I think it makes for more readable code to avoid pointer typedefs, but I mention this so you can make sense of other suggestions.

Casting with (int (**)(int, int)) might seem to do the trick now, but it invokes Undefined Behavior !

Converting void* to function pointer is not Standard C.

Note that aliasing void* to a different type; a strict aliasing violation. Read more in What is the effect of casting a function pointer void?

Please consider using an array of function pointers from the start.

function is an array of pointers to data of type void . You want to cast it to a pointer to pointers of type int (*)(int, int) which would be int (**)(int, int) , so the following works:

int (*F)(int, int) = ((int (**)(int, int)) functions)[0];

As pointed out by @MM , the above will result in undefined behaviour . You might want to read this post and this for more on that.


Ideally, you would do something like this:

// Array of 2 pointers to functions that return int and takes 2 ints
int (*functions[2])(int, int) = {&foo, &bar};

// a pointer to function
int (*F)(int, int) = functions[0];
int r = F(3, 4);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM