Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
292 views
in Technique[技术] by (71.8m points)

c++ - Locally disable padding

I write a parser for some data structure, after hours of debugging I found out that the problem is Visual Studio doesn't interpret the structures as I tell it. It seems some "padding" is used

struct foo { 
unsigned char a; //0x00
unsigned char b; //0x01
unsigned int c; //0x02
unsigned int d; //0x06
unsigned int e; //0x0A
unsigned int f; //0x0E
//0x12
};

I expected "sizeof(foo)=4*4+2=18" but I get "sizeof(foo)=20". Is there any possibility to turn padding off just for this special struct? I tried

__declspec(align(1)) struct foo { ...

but it does not work. Thank you for your help.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Use the #pragma pack directive for that:

#pragma pack(push, 1)
struct foo { 
  // etc..
};
#pragma pack(pop)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...