Is it possible to cast struct pointer to function pointer in c?

1

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 finall function is void(*)() type, but I would like to make cast available to other function "types" that can forexample 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));
}

Unfortunatelly, it gives an error:

invalid use of void expression

So the question is, how to cast back the type (void*) to (int*)(int,int)? in the printf statement?

answered question

1 Answer

5

In your example, you have the function you are casting to returning a (void*) or a "pointer to a void". That's why the compiler is complaining, you can't return a pointer to nothing.

Don't shift the type signature from (void)(func)(void) to (void)(*func)(void) and you'll have better success in your casting. I'm not sure why you would want to do a cast like this, as to use the function properly, you'd have to cast it back to it's original signature; but, the cast should be permitted.

posted this

Have an answer?

JD

Please login first before posting an answer.