问题
I'm having getting the above warning and understand it, but just don't know how to fix it. My code is below, but basically what I'm doing is storing a function pointer in a struct, and initializing the struct in another function that I call from my main. The code seems to compile when I use it with a default function (i.e. free()) but not when I use it with the test_func function below. Thoughts?
Struct:
typedef struct my_struct {
my_type **double_pointed;
int num;
void (*funcp)(void *data);
} my_struct_t;
Init function:
my_struct_t *init(int num, void (*my_funcp)(void *data)) {
// unimportant code to the problem, but basically just some mallocs for the other data
my_struct_t *my_str;
my_str->funcp = my_funcp;
return struct;
}
function I want to point to:
void desired_func(my_type *obj) {}
my call to the init func:
init(5, desired_func);
full error:
incompatible pointer types assigning to 'void (*)(void *)' from 'void (my_type *)'
on the line in the init function above:
my_struct_t *my_str;
my_str->funcp = my_funcp;
回答1:
Change the function pointer types to match the function, ie. :
void (*funcp)(my_type *data);
If you want to be able to use functions with different signatures (eg. different parameter types), you can add explicit casts. For example :
init(5, (void (*)(void*)) desired_func);
Note that any time the desired_func
function (or any other function whose signature doesn't match the funcp
function pointer) needs to be called through the function pointer, the function pointer will have to be cast back to its original type (void (*)(my_type*)
in this case) before calling the function, or it invokes undefined behavior.
Another (somewhat better) alternative is to change the desired_func
definition like this :
void desired_func(void *vobj) {
my_type* obj = vobj;
/* rest of the code */
}
Note that when calling desired_func
(through a function pointer or directly), the type of the object whose address is passed as parameter needs to be my_type
, or dereferencing obj
inside the function (and if alignment differs even the cast itself) will invoke undefined behavior.
The added complexity for dealing with the potential for undefined behavior when casting (as noted above) means that I would advise against casting - needing such casts is probably indicative of a problem in your design. Ie. there's probably a better solution if you think about your requirements a bit more.
来源:https://stackoverflow.com/questions/38474800/function-pointer-incompatible-pointer-types-void-void-from-void-my-type