.net - .NET 中数组的对齐方式

标签 .net arrays clr alignment

.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 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.

...

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/

相关文章:

.net - 编译器生成的 GetHashCode()

php - 如何从多维数组中删除重复项和原始数组?

c# - 局部变量实际上在 CLR 中分配在哪里?

c# - Directory.EnumerateFiles 和 File.Exists 忽略 native DLL 文件

.net - 想要在 .NET 中使用数据库而不安装数据库引擎

c# - 在 C# 中引用多个 Web 服务时解决类型歧义

python - ReplyKeyboardMarkup 对 python 不起作用?

javascript - 如何使用一个数组元素作为另一个数组的索引

c++ - 错误 LNK2019 : unresolved external symbol "extern "C"what is this error?

c# - 在没有代码签名的情况下从文件共享运行 .NET 应用程序