Lets say I have the following code in 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.
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()
.
You can use 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
#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);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.