假设我在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);
如何在没有指针转换警告的情况下编译它,而无需手动抑制某些错误?
稍后编辑:我试图不修改funct_type1()和func_type2()定义。
答案 0 :(得分:0)
正确的解决方法是将特定于实现的内容折叠到抽象接口“后面”的函数中,即:
void funct_type1(void *s1)
{
struct something1 *s = s1;
/* ... rest of function ... */
}
否则你将不得不在调用general()
。
答案 1 :(得分:0)
您可以使用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);
,其中
void funct_type1(void* something)
{
struct something1 *castedPointer = something;
//...YOUR STUFF
}
或者您可以使用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);
}