转换具有不同指针类型的函数指针作为参数 [英] Casting function pointers with different pointer types as an argument

查看:136
本文介绍了转换具有不同指针类型的函数指针作为参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我认为以下代码描述了我要执行的操作.具体来说,我希望将函数指针转换为通用函数类型,而签名的唯一区别就是不同的指针类型.

The following code, I think, describes what I am trying to do. Specifically, I wish to cast a function pointer to a generic function type, with the only difference in signature being different pointer types.

现在,我知道功能指针必须兼容 ,如

Now, I'm aware that there is a requirement for function pointers to be compatible as discussed in this question, but I'm not sure whether having an argument of different pointer type satisfies that compatibility requirement.

该代码可以编译并运行,但是,正如预期的那样,会发出有关来自不兼容指针类型的分配的警告.有什么方法可以使编译器满意并实现我的追求吗?

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

#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;
}

推荐答案

最干净的方法是恕我直言,在内部执行 强制转换功能.这将强制所有功能签名都相同,并使强制类型转换不包含在调用者的代码中. (例如,这是qsort()想要的方式)

The cleanest way is IMHO to perform the cast inside the function. This will force all the function signatures to be the same, and keeps the casts out of the caller's code. (this is for instance the way that qsort() wants it)

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;
}

这篇关于转换具有不同指针类型的函数指针作为参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆