D 关于';对齐';属性

D 关于';对齐';属性,d,dmd,D,Dmd,我知道align属性有一种用法 在我的第一次尝试中,我使用它如下: align(1) private struct TGAHeader { ubyte idLenght; ubyte hasColormap; ubyte imageType; ushort cmFirstEntry; ushort cmLength; ubyte cmSize; ushort xOrigin; usho

我知道
align
属性有一种用法

在我的第一次尝试中,我使用它如下:

align(1)
private struct TGAHeader
{
    ubyte  idLenght;  
    ubyte  hasColormap;
    ubyte  imageType;  
    ushort cmFirstEntry;
    ushort cmLength;    
    ubyte  cmSize;      
    ushort xOrigin;      
    ushort yOrigin;       
    ushort width;          
    ushort height;          
    ubyte  pixelDepth;      
    ubyte  imageDescriptor; 
}

// TGAHeader.sizeof == 20
这导致结构中额外填充了2个不需要的字节

将其更改为:

private struct TGAHeader
{
align(1):
    ubyte  idLenght;  
    ubyte  hasColormap;
    ubyte  imageType;  
    ushort cmFirstEntry;
    ushort cmLength;    
    ubyte  cmSize;      
    ushort xOrigin;      
    ushort yOrigin;       
    ushort width;          
    ushort height;          
    ubyte  pixelDepth;      
    ubyte  imageDescriptor; 
}

// TGAHeader.sizeof == 18
我得到了预期的18个字节的头大小


因此,我的疑问是:如果
align
属性的第一种形式似乎不像人们期望的那样对齐数据,那么它的实际用途是什么

聚合字段的对齐方式不影响聚合本身的对齐方式,这受聚合外部的对齐方式设置的影响

因此,第二个表单对齐结构的字段。第一个对齐结构本身

在你的例子中,考虑一个更大的对齐方式,比如说16。第一个表单将生成以下布局

TGAHeader.sizeof                   = 32   // the padding was added in the end of the struct  
TGAHeader.idLenght.offsetof        = 0
TGAHeader.hasColormap.offsetof     = 1
TGAHeader.imageType.offsetof       = 2
TGAHeader.cmFirstEntry.offsetof    = 4
TGAHeader.cmLength.offsetof        = 6
TGAHeader.cmSize.offsetof          = 8
TGAHeader.xOrigin.offsetof         = 10
TGAHeader.yOrigin.offsetof         = 12
TGAHeader.width.offsetof           = 14
TGAHeader.height.offsetof          = 16
TGAHeader.pixelDepth.offsetof      = 18
TGAHeader.imageDescriptor.offsetof = 19
第二种形式将导致

TGAHeader.sizeof                   = 192 // every field was padded
TGAHeader.idLenght.offsetof        = 0
TGAHeader.hasColormap.offsetof     = 16
TGAHeader.imageType.offsetof       = 32
TGAHeader.cmFirstEntry.offsetof    = 48
TGAHeader.cmLength.offsetof        = 64
TGAHeader.cmSize.offsetof          = 80
TGAHeader.xOrigin.offsetof         = 96
TGAHeader.yOrigin.offsetof         = 112
TGAHeader.width.offsetof           = 128
TGAHeader.height.offsetof          = 144
TGAHeader.pixelDepth.offsetof      = 160
TGAHeader.imageDescriptor.offsetof = 176