分享

#pragma pack()

 WUCANADA 2014-03-27
 (Very ) Basically the compiler unless otherwise directed will line up structure members on
2 byte or 4 byte boundaries - this makes it easier and faster for the processor to handle.
So the structure contains secret padding bytes to make this happen.

The pragma pack directive (in MS Compiler) allows you to change this alignment scheme.

Some things (particularly in relation to hardware) do not have the luxury to waste bytes like
this and they send their data in an exact fit.
This means that it is not wise to read data from a hardware device directly into a normal structure.

If you have want to read data that is an exact fit into a structure - you can tell the compiler
to make the structure an exact fit like this (microsoft compiler);
1
2
3
4
5
6
7
8
#pragma pack(push, 1) // exact fit - no padding
struct MyStruct
{
  char b; 
  int a; 
  int array[2];
};
#pragma pack(pop) //back to whatever the previous packing mode was 


Without the pragma directive, the size of the structure is 16 bytes - with the packing of 1 - the size is 13 bytes 

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多