2014-06-25 19 views
6

Tôi hiểu rằng thuộc tính align có hình thức sử dụng few different.Lẫn lộn về thuộc tính 'căn chỉnh'

Trong nỗ lực đầu tiên của tôi, tôi đã sử dụng nó như sau:

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 

nào dẫn đến việc struct được đệm bằng 2 byte thêm không mong muốn.

Sau khi thay đổi nó để:

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 

tôi đã dự kiến ​​18 byte cho kích thước tiêu đề. Vì vậy, nghi ngờ của tôi là: Việc sử dụng thực tế của hình thức đầu tiên của thuộc tính align là gì nếu nó dường như không căn chỉnh dữ liệu như mong đợi?

Trả lời

7

Trích từ liên kết mà bạn đã đưa ra:

Sự sắp xếp cho các lĩnh vực của một tổng hợp không ảnh hưởng đến sự liên kết của các tổng hợp - mà bị ảnh hưởng bởi các thiết lập sự liên kết bên ngoài của tổng thể.

Vì vậy, biểu mẫu thứ hai sẽ căn chỉnh các trường của cấu trúc. Và lần đầu tiên căn chỉnh cấu trúc.

Trong ví dụ của bạn, hãy xem xét một sự liên kết lớn hơn - nói, trong 16. Các hình thức đầu tiên sẽ dẫn đến việc bố trí sau

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 

Và hình thức thứ hai sẽ dẫn đến

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