Search code examples
cgenericsc11cortex-mstm32f7

Generic function typedef in C - how to get rid of initialization warning?


I'm experimenting with generic-like code and I have a function like this (a lot of not relevant code removed):

typedef uint8_t (*struct_converter_t)(void *, char *);

void convert_struct(
        struct_converter_t converter, // this is a function
        const char * file_name
){
    some_struct_t * some_struct;
    converter(some_struct, some_string_buffer);
}

And when I try to assign a function that takes some_struct_t (not void *):

static uint8_t some_converter(some_struct_t * vd, char * s);

to my struct_converter_t like this:

struct_converter_t converter = some_converter;    // WARNING HERE

I'm getting this:

initialization of 'struct_converter_t' {aka 'unsigned char (*)(void *, char *)'} from incompatible pointer type 'uint8_t (*)(some_struct_t *, char *)' {aka 'unsigned char (*)(struct <anonymous> *, char *)'} [-Wincompatible-pointer-types]

I'm not experienced in C and I would like to know if there is a way to get rid of this warning elegantly.


Solution

  • The function that you're assigning to the function pointer type has parameters that are incompatible with the function pointer.

    Your function takes a some_struct_t * as the first parameter but the function pointer type takes a void * as the first parameter. While any object pointer can be converted to/from a void *, that does not extend to function pointer parameters.

    You need to change your function to take a void * for its first parameter to be compatible with the function pointer. Then inside the function you can convert that void * parameter to a some_struct_t *.