From here: ISO C Void * and Function Pointers, I have found a workaround to cast (void*) to function pointer:
int
main(int argc, char *argv[])
{
...
void (*funcp)(void); /* Pointer to function with no arguments */
...
*(void **) (&funcp) = dlsym(libHandle, argv[2]);
}
In other words - to dereference double pointer (another level of indirection).
Now that still assumes, that the final function is of void(*)() type, but I would like to make cast available to other function "types" that can for example accepts some arguments.
Then I found another workaround how to wrap function pointer in struct Why can't I cast a function pointer to (void *)? :
typedef struct
{
void (*ptr)(void);
} Func;
Func vf = { voidfunc };
So I would like to merge these 2 ideas and make possible to pass arbitrary function type as function pointer via struct:
#include <stdio.h>
struct s{
int a, b;
void (*func)();
};
typedef struct{
int (*add)(int,int);
} Func;
int add(int a, int b) { return a+b; }
int main(){
Func f = {add};
struct s foo = {.func=(void*)(&f)};
printf("%i\n",f.add(1,2));
printf("%i\n",foo.func(1,2));
}
Unfortunately, it gives the error:
invalid use of void expression
So the question is, how to cast back the type (void*) to (int*)(int,int) inside of the printf statement?
void *to a function pointer, because you can just write the cast:void (*funcp)(void) = (void (*)(void)) dlsym(libHandle, argv[2]);. That is not defined by the C standard, but it is allowed. If you are working in an environment that supportsdlsym, which is documented to return avoid *that is the address of code or data, then that environment necessarily supports convertingvoid *to… - Eric Postpischilvoid *to a function pointer, it is going to do it through a simple cast—it is unlikely any implementation would not support that but would support it through reinterpreting the bits of the pointer as you are doing. That adds other problems with representations and aliasing. - Eric Postpischildlsyminto an appropriate pointer-to-function type. I don't understand what you're trying to do with the structs but it seems like an XY problem. - interjay(void*)to(int*)(int,int)? in the printf statement?”: Do not do that. There is no reason for it. To print any pointer, use%p, not%i, and convert it tovoid *, if it is not already. - Eric Postpischil