.NET 中的数组是否与任何边界对齐?
如果是,是哪一个?所有数组类型都一样吗?
最佳答案
公共(public)语言基础设施 (ECMA-335) 对对齐设置了以下限制:
12.6.2 Alignment
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 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 还指定您可以使用 unaligned
前缀来允许任意对齐。此外,无论实际对齐如何,JIT 都必须生成正确的代码来读取和写入。
此外,CLI 允许类字段的显式布局:
explicitlayout
: A class markedexplicitlayout
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....
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
.
关于.net - .NET 中数组的对齐方式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9741395/