简体   繁体   English

C从特定函数指针转换为不太具体的函数指针

[英]C cast from specific function pointer to less specific function pointer

Lets say I have the following code in C: 假设我在C中有以下代码:

void general(void (*function)(void *something), void *something);
void funct_type1(struct something1 *something);
void funct_type2(struct something2 *something);
general(funct_type1, something1);
general(funct_type2, something2);

How do I compile this without pointer conversion warnings, and without manually suppressing some errors? 如何在没有指针转换警告的情况下编译它,而无需手动抑制某些错误?

Later edit: I'm trying not to modify funct_type1() and func_type2() definition. 稍后编辑:我正在尝试不修改funct_type1()和func_type2()定义。

The proper fix is to fold the implementation-specific things into the function "behind" the abstract interface, ie: 正确的解决方法是将特定于实现的东西折叠到抽象接口“后面”的函数中,即:

void funct_type1(void *s1)
{
 struct something1 *s = s1;
 /* ... rest of function ... */
}

Otherwise you're going to have to cast the function pointer in the calls to general() . 否则,您将不得不在对general()的调用中强制转换函数指针。

You can use void * 你可以使用void *

void general(void (*function)(void *something), void *something);
void funct_type1(void* something);
void funct_type2(void* something);
general(funct_type1, &test1);
general(funct_type2, &test2);

where 哪里

void funct_type1(void* something)
{
   struct something1 *castedPointer = something;

//...YOUR STUFF
}

Or you can use an union to group your structs 或者您可以使用union对结构进行分组

#include <stdio.h>

struct something1
{
    int a;
};

struct something2
{
    int b;
};

union something3
{
    struct something1 s1;
    struct something2 s2;
};

void general(void (*function)(union something3 *something), union something3* something)
{
    if (function != NULL)
        function(something);
}

void funct_type1(union something3* something)
{
    something->s1.a = 1;

    printf("%s - something->s1.a = %d\n", __func__, something->s1.a);
}

void funct_type2(union something3* something)
{
    something->s2.b = 3;

    printf("%s - something->s2.b = %d\n", __func__, something->s2.b);
}

int main()
{
    union something3 test1;
    union something3 test2;

    test1.s1.a = 0;
    test2.s2.b = 0;

    general(funct_type1, &test1);
    general(funct_type2, &test2);

    printf("%s - test1.s1.a = %d\n", __func__, test1.s1.a);
    printf("%s - test2.s2.b = %d\n", __func__, test2.s2.b);

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM