[英]void * cast for generic function
I'm trying to build a generic function as the one below我正在尝试构建一个通用的 function 如下所示
struct x {
int l;
char p;
};
struct y {
int l;
char p;
};
void test (void *t, int type)
{
if (type)
(struct y*)t;
else
(struct x*)t;
t->l = 6;
t->p = 'k';
}
Something like this, the variable t must have the same name for cast x* or y*.像这样,变量 t 必须与 cast x* 或 y* 具有相同的名称。 Do you have any idea if this is possible or have other suggestions?
您是否知道这是否可行或有其他建议? Thank you!
谢谢!
This:这个:
(struct y*)t;
Doesn't permanently change the type of t
.不会永久更改
t
的类型。 It takes the value of t
, converts the type of that value from void *
to struct y *
, then discards that value since nothing is done with it.它获取
t
的值,将该值的类型从void *
转换为struct y *
,然后丢弃该值,因为没有对其进行任何处理。
After converting the pointer value, you can then dereference the resulting expression and assign to the appropriate member.转换指针值后,您可以取消引用结果表达式并分配给适当的成员。
if (type)
((struct y*)t)->l = 1;
else
((struct x*)t)->l = 1;
Alternately, you can assign the value of t
to a variable of the appropriate type and use that going forward:或者,您可以将
t
的值分配给适当类型的变量并在以后使用:
if (type) {
struct y *y1 = t;
y1->l = 1;
// do more with y1
} else {
struct x *x1 = t;
x1->l = 1;
// do more with x1
}
If what you want is to work on two structs that have some common members, you need to create a separate struct with the common members and include that in each of the two structs.如果您想要处理具有一些公共成员的两个结构,则需要创建一个具有公共成员的单独结构,并将其包含在两个结构中的每一个中。
struct z {
int l;
char p;
};
struct x {
struct z z;
int i;
};
struct y {
struct z z;
double j;
};
void test(struct z *t)
{
t->l = 6;
t->p = 'k';
}
int main()
{
struct x x1;
struct y y1;
test((struct z*)&x1);
test((struct z*)&y1);
}
The above cast is allowed because a pointer to a struct can be safely converted to a pointer to its first member.上面的强制转换是允许的,因为指向结构的指针可以安全地转换为指向其第一个成员的指针。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.