cpp
#include <iostream>
#define FIELDOFFSET(TYPE, MEMBER) (int)(&(((TYPE*)0)->MEMBER))
//0可以转换为任意类型的结构体或空对象
#pragma pack(push)
#pragma pack(1)
struct Info
{
char username[10];//24-34
double userdata;//40-48
};
#pragma pack(pop)//会变成18
struct Frame
{
unsigned char id;//0-1
int width;//4-8
long long height;//8-16
unsigned char* data;//16-20
Info info;//24-48
};
int main()
{
int len2 = sizeof(Info);//子结构体改变
int len = sizeof(Frame);//母结构体不改变
int offset_w = FIELDOFFSET(Frame, width);
int offset_h = FIELDOFFSET(Frame, height);
int offset_d = FIELDOFFSET(Frame, data);
int offset_i = FIELDOFFSET(Frame, info);
/*len = sizeof(Info);*/
return 0;
}
1.定义0计算偏移量
cpp
#define FIELDOFFSET(TYPE, MEMBER) (int)(&(((TYPE*)0)->MEMBER))
int offset_w = FIELDOFFSET(Frame, width);
2.结构体入栈出栈
#pragma pack(push)
#pragma pack(1)
struct Info
{
char username[10];//24-34
double userdata;//40-48
..........
};
#pragma pack(pop)//会变成18