[英]Structures containing conditional fields in C
我正在尝试实现协议标准,但是对于它们的条件字段的概念有些麻烦。 它们被定义为根据某些条件存在或不存在的字段。 他们给出的示例如下:
uint16 Pressure;
enum VehicleType { car = 0, motorbike = 1};
struct TirePressureInfo {
VehicleType type;
select (type)
{
case car:
Pressure frontLeft;
Pressure frontRight;
Pressure rearLeft;
Pressure rearRight;
case motorbike:
Pressure front;
Pressure rear;
}
}
无论如何,我仍然不知道是否可以使用C进行这项工作,甚至是不可能的。 无论如何我都想不到要实现这一点。 需要注意的一件事是,这将在Linux内核模块中实现,因此我在这里也受到一些限制。
struct {
uint8 protocol_version;
ContentType type;
select (type) {
case unsecured :
opaque data<var>;
case signed, signed_partial_payload,
signed_external_payload:
SignedData signed_data;
case signed_wsa:
SignedWsa signed_wsa;
case encrypted :
EncryptedData encrypted_data;
case crl_request :
CrlRequest crl_request;
case crl :
Crl crl;
case other_value:
opaque data<var>;
}
} 1609Dot2Data;
struct {
SignerIdentifierType type;
select (type) {
case self: ;
case certificate_digest_with_ecdsap224 :
case certificate_digest_with_ecdsap256 :
HashedId8 digest;
opaque data<var>;
case certificate:
Certificate certificate;
case certificate_chain:
Certificate certificates<var>;
case certificate_digest_with_other_algorithm :
Signer signer;
PKAlgorithm algorithm;
HashedId8 digest;
case other_value:
opaque id<var>;
}
} SignerIdentifier;
您可以使用union
:
uint16 Pressure;
enum VehicleType { CAR = 0, MOTORBIKE = 1};
struct TirePressureInfo {
VehicleType type;
union {
struct {
Pressure frontLeft;
Pressure frontRight;
Pressure rearLeft;
Pressure rearRight;
} car;
struct {
Pressure front;
Pressure rear;
} motorbike;
} data;
};
因此,您可以将其设置为:
struct TirePressureInfo info;
info.type = CAR;
info.data.car.frontLeft = 35;
info.data.car.frontRight = 35;
info.data.car.rearLeft = 32;
info.data.car.rearRight = 32;
或者如果您想定义一个MOTORBIKE
:
struct TirePressureInfo info;
info.type = MOTORBIKE;
info.data.motorbike.front = 38;
info.data.motorbike.rear = 40;
从中读取时,应检查type
:
switch ( info.type ) {
case CAR:
/* read info.data.car fields */
break;
case MOTORBIKE:
/* read info.data.motorbike fields */
break;
default:
/* Some data integrity problem */
}
如果你确信你永远只需要一个struct car
或struct motorbike
在同一时间(取决于价值type
),那么就没有必要通过为每一个空间的浪费TirePressureInfo
包括 struct car
的领域和struct motorbike
“的字段。 使用union
使struct car
和struct motorbike
在内存中占据相同的位置。 在实际大小union
是两个更大 。 这只是为您提供了不同的方式来读取和写入内存中的同一位置。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.