我必须在道具上工作。二进制文件格式,想用结构体来实现。
我的结构中需要恒定的字节序列,而 atm 我不知道如何实现这一点。
我想过这样的事情:
#include <cstdint>
#pragma pack(push,1)
typedef struct PAYLOAD_INFO {
const uint8_t magicnumber[4] = { 0xFA, 0x11 , 0x28 , 0x33 };
uint16_t UMID;
const uint16_t VID = 1487 ;
uint32_t crc;
};
#pragma pack(pop)
int main (){
PAYLOAD_INFO pldInst;
pldInst.UMID = 5;
pldInst.crc = 0x34235a54;
...
writeToFile(&PAYLOAD_INFO,sizeof(PAYLOAD_INFO));
}
最后“pldInst”应该看起来像那样(在内存中),而不考虑本示例中的字节顺序:
0x00000000: 0xFA, 0x11 , 0x28 , 0x33
0x00000004: 0x00, 0x05 , 0x05 , 0xCF
0x00000008: 0x34, 0x23 , 0x5a , 0x54
我已经尝试过“默认”方法:
#include <cstdint>
#pragma pack(push,1)
typedef struct PAYLOAD_INFO {
static const uint8_t magicnumber[4];
uint16_t UMID;
static const uint16_t VID = 1487 ;
uint32_t crc;
};
const uint8_t magicnumber[4] = { 0xFA, 0x11 , 0x28 , 0x33 };
#pragma pack(pop)
但没有按预期工作。
有没有办法在不计算每个结构成员的内存大小、分配新内存和复制每个成员的情况下完成这项工作?
我使用 g++ 4.6.3。
问候,托马斯
更新:
@bikeshedder 提供的 c++11 解决方案运行良好,但只能使用 g++ 4.7 或更高版本进行编译。