Cast function pointers with various types of pointers as an argument

The following code, I think, describes what I'm trying to do. In particular, I want to use a function pointer to a generic function type, with the only difference being that signatures are different types of pointers.

Now I know that there is a requirement that function pointers are compatible, as discussed in this question , but I'm not sure if there is an argument of a different type of pointer that satisfies compatibility requirements.

The code compiles and runs, but, as expected, gives warnings about the assignment from an incompatible pointer type. Is there a way to satisfy the compiler and achieve what I want?

#include <stdio.h>

int float_function(float *array, int length)
{
    int i;
    for(i=0; i<length; i++){
        printf("%f\n", array[i]);
    }
}

int double_function(double *array, int length)
{
    int i;
    for(i=0; i<length; i++){
        printf("%f\n", array[i]);
    }
}


int main() 
{
    float a[5] = {0.0, 1.0, 2.0, 3.0, 4.0};    
    double b[5] = {0.0, 1.0, 2.0, 3.0, 4.0};

    int (*generic_function)(void*, int) = NULL;

    generic_function = &float_function;
    generic_function(a, 5);

    generic_function = &double_function;
    generic_function(b, 5);

    return 0;
}
+5
source share
3

- , . , . (, , , qsort())

int double_function(void *p, unsigned size)
{
    double *array = p    
    unsigned uu;

    for(uu=0; uu < size; uu++){
        printf("%f\n", array[uu]);
    }
return 42;
}
+5

, .

int (*generic_function)() = NULL;

, int, .

+2

EDIT: @Mat, C, , ;

((int(*)(float*,int))generic_function)(a, 5);

( @wildplasser) , , void *, . :

#define WRAP(FN, TYPE) int FN##_wrapped(void* p, int len) { return FN((TYPE*)p, len); }
WRAP(float_function, float)
WRAP(double_function, double)

Then, instead, you can use the following pretty clean lines:

generic_function = float_function_wrapped;
generic_function(a, 5);

However, casting a pointer is usually not a solution that I would defend, but it has its own use cases.

+1
source

All Articles