作为构建.NET的标准,CLI Spec(ECMA-335)针对基元类型的对齐规则具有如下的描述。按照这个标准,我们是这么理解的:8字节的数据类型(int64、unsigned int64和float64)根据采用的机器指令架构选择4字节或者8字节对其。进一步来说,它们在x86/x64机器上的对其字节分别为4字节和8字节。
Built-in data types shall be properly aligned, which is defined as follows:
1-byte, 2-byte, and 4-byte data is properly aligned when it is stored at a 1-byte, 2-byte, or 4-byte boundary, respectively.
8-byte data is properly aligned when it is stored on the same boundary required by the underlying hardware for atomic access to a
native int
.Thus,
int16
andunsigned int16
start on even address;int32
,unsigned int32
, andfloat32
start on an address divisible by 4; andint64
,unsigned int64
, andfloat64
start on an address divisible by 4 or 8, depending upon the target architecture. The native size types (native int
,native unsigned int
, and&
) are always naturally aligned (4 bytes or 8 bytes, depending on the architecture). When generated externally, these should also be aligned to their natural size, although portable code can use 8-byte alignment to guarantee architecture independence. It is strongly recommended thatfloat64
be aligned on an 8-byte boundary, even when the size ofnative int
is 32 bits.
我们通过一个简单控制台程序来验证这个说法。为了在64位机器上模拟32位平台,我们按照如下的方式修改了.csproj文件,将PlatformTarget属性设置为x86(默认为Any CPU)。
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</Ou