在.NET数组对齐数组、NET

2023-09-03 05:39:10 作者:七月蔚蓝╯

是.NET数组任意边界对齐?

Are arrays in .NET aligned to any boundary?

如果有,要哪个?而且是相同的所有数组类型?

If yes, to which? And is it the same for all array types?

推荐答案

公共语言基础架构(ECMA-335)则以下列限制调整:

The common language infrastructure (ECMA-335) places the following restrictions on alignment:

12.6.2对齐

内置数据类型应被适当地对准,其定义如下:

Built-in data types shall be properly aligned, which is defined as follows:

   1字节,2字节,4字节,当它被存放在一个1字节,2字节的数据被正确对齐,或4字节的边界,分别   当它被存储在由原子访问到本机的int底层硬件所需要的相同的边界上 8字节数据被正确对准。    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.

因此​​,INT16和无符号INT16开始在偶数地址; INT32,无符号INT32和FLOAT32开始地址被4整除;和int64类型,无符号int64类型,并float64启动上的地址被4除尽或8,取决于目标体系结构。本机尺寸类型(本地INT,固有无符号整型,并与放大器;)总是自然对齐(4字节或8个字节,根据架构)。当产生的外部,这些也应该对准其自然大小,虽然便携式code可以使用8字节对齐,以保证结构是独立的。强烈建议float64将在8字节边界对齐,即使在本​​土int的长度为32位。

Thus, int16 and unsigned int16 start on even address; int32, unsigned int32, and float32 start on an address divisible by 4; and int64, unsigned int64, and float64 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 that float64 be aligned on an 8-byte boundary, even when the size of native int is 32 bits.

CLI还规定,您可以使用对齐 preFIX允许abritrary对齐。此外,JIT必须出示正确的code读写不顾实际比对。

The CLI also specifies that you can use an unaligned prefix to allow for abritrary alignment. Furthermore, the JIT must produce correct code to read and write regardless of the actual alignment.

此外,CLI的允许类领域的显式布局:

Additionally, the CLI allows for the explicit layout of class fields:

   explicitlayout :标有A类 explicitlayout 使加载程序忽略场序列和使用提供明确的布局规则,在字段偏移和/或整个班级规模或比对的形式。上有有效的布局,在分区二所规定的限制。    explicitlayout: A class marked explicitlayout causes the loader to ignore field sequence and to use the explicit layout rules provided, in the form of field offsets and/or overall class size or alignment. There are restrictions on valid layouts, specified in Partition II.

...

任选地,一个开发者可以指定一个包装尺寸的一类。这是不经常使用的布局信息,但它允许开发以控制字段的取向。它不是一个对准说明书中,本身,而是作为其放置在所有比对天花板的改性剂。典型值是1,2,4,8,或16泛型类型,不得被标记 explicitlayout

Optionally, a developer can specify a packing size for a class. This is layout information that is not often used, but it allows a developer to control the alignment of the fields. It is not an alignment specification, per se, but rather serves as a modifier that places a ceiling on all alignments. Typical values are 1, 2, 4, 8, or 16. Generic types shall not be marked explicitlayout.