[英]C cast from specific function pointer to less specific function pointer
假設我在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()定義。
正確的解決方法是將特定於實現的東西折疊到抽象接口“后面”的函數中,即:
void funct_type1(void *s1)
{
struct something1 *s = s1;
/* ... rest of function ... */
}
否則,您將不得不在對general()
的調用中強制轉換函數指針。
你可以使用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);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.