才下眉头 發表於 2025-12-3 08:42:31

.NET 结构体字段的内存布局深度解析

<div id="navCategory"><h5 class="catalogue">目录</h5><ul class="first_class_ul"><li><a href="#_label0">前言</a></li><li><a href="#_label1">基本概念</a></li><li><a href="#_label2">结构体的默认字段布局</a></li><ul class="second_class_ul"><li><a href="#_lab2_2_0">对齐</a></li><li><a href="#_lab2_2_1">64 位系统与 32 位系统的对齐要求差异</a></li><li><a href="#_lab2_2_2">默认字段布局中 对齐要求 与 偏移量 的关系</a></li></ul><li><a href="#_label3">填充</a></li><ul class="second_class_ul"></ul><li><a href="#_label4">包含引用类型字段的结构体的默认字段布局</a></li><ul class="second_class_ul"></ul><li><a href="#_label5">用StructLayoutAttribute控制字段布局</a></li><ul class="second_class_ul"></ul><li><a href="#_label6">LayoutKind.Sequential</a></li><ul class="second_class_ul"><li><a href="#_lab2_6_3">Pack 为 0 时等于默认布局</a></li><li><a href="#_lab2_6_4">Pack 不为 0 时,取 Pack 和 字段类型大小 的较小值</a></li><li><a href="#_lab2_6_5">Pack 设置为 1 时,会形成密集的字段布局</a></li><li><a href="#_lab2_6_6">Pack 不为 0 的结构体作为其他结构体字段时</a></li></ul><li><a href="#_label7">LayoutKind.Explicit</a></li><ul class="second_class_ul"><li><a href="#_lab2_7_7">Pack 为 0 时,结构体按照最大字段默认对齐要求对齐</a></li><li><a href="#_lab2_7_8">Pack 不为 0 时,结构体实例按照 Pack 与 最大字段对齐要求 的较小值对齐</a></li><li><a href="#_lab2_7_9">将 Pack 属性设置为 1 可以消除结构体实例的末尾填充</a></li><li><a href="#_lab2_7_10">Pack 属性不为 0 的结构体作为其他结构体字段时</a></li></ul><li><a href="#_label8">LayoutKind.Auto</a></li><ul class="second_class_ul"></ul><li><a href="#_label9">作为数组元素时的结构体实例</a></li><ul class="second_class_ul"><li><a href="#_lab2_9_11">默认字段布局</a></li><li><a href="#_lab2_9_12">非默认字段布局</a></li></ul></ul></div><p class="maodian"><a name="_label0"></a></p><h2>前言</h2>
<p>大部分情况下我们并不需要关心结构体字段的内存布局,但是在一些特殊情况下,比如性能优化、和非托管代码交互、对结构体进行序列化等场景下,了解字段的内存布局是非常重要的。</p>
<p>本文写作时 最新的 .NET 正式版是 .NET 9,以后的版本不保证本文内容的准确性,仅供参考。</p>
<p>本文将介绍 .NET 中结构体字段的内存布局,包括字段的对齐(Alignment)、填充(Padding)以及如何使用 <code>StructLayoutAttribute</code> 来控制字段的内存布局。</p>
<p>对齐的目的是为了 CPU 访问内存的效率,64 位系统和 32 位系统中对齐要求存在差异,下文如果没有特别说明,均指 64 位系统。</p>
<p>填充则是为了满足对齐要求而在字段之间或结构体末尾添加的额外字节。</p>
<p>结构体的对其规则同时适用于栈上和堆上的结构体结构体实例,方便起见,大部分例子将使用栈上结构体实例来演示。</p>
<p>一些资料是从 字段的偏移量(offset)为出发点来介绍字段的内存布局的,但笔者认为从字段的 内存地址 出发更容易理解。</p>
<p>由于一些资料并没有找到明确的官方的解释,笔者是在实验和推导的基础上总结出这些规则的,可能会有不准确的地方,欢迎读者在评论区指出。</p>
<p>本文虽然没有直接介绍引用类型的字段布局,但引用类型实例的字段的内存布局概念与结构体实例的内存布局是相同的。不同之处在于引用类型的默认布局是 <code>LayoutKind.Auto</code>,而结构体的默认布局是 <code>LayoutKind.Sequential</code>。读者可以自己尝试观察引用类型实例字段的内存布局。</p>
<p>本文将使用下面的方法来观察字段的内存地址:</p>
<div class="jb51code"><pre class="brush:csharp;">// 打印日志头
void PrintPointerHeader()
{
    Console.WriteLine(
      $"| {"Expr",-15} | {"Address",-15} | {"Size",-4} | {"AlignedBySize",-13} | {"Addr/Size",-12} |");
}
// 打印指针的详细信息
unsafe void PrintPointerDetails&lt;T&gt;(
    T* ptr,
    string? pointerExpr = null)
    where T : unmanaged
{
    ulong addressValue = (ulong)ptr;
    ulong typeSize = (ulong)sizeof(T);
    decimal addressDivBySize = addressValue / (decimal)typeSize;
    bool isAlignedBySize = addressValue % typeSize == 0;
    Console.WriteLine(
      $"| {pointerExpr,-15} | {addressValue,-15} | {typeSize,-4} | {isAlignedBySize,-13} | {addressDivBySize,-12:0.##} |"
    );
}</pre></div>
<p>并使用 ObjectLayoutInspector 这个开源库来观察字段的内存布局。</p>
<p>项目地址:<a href="https://github.com/SergeyTeplyakov/ObjectLayoutInspector" rel="noopener nofollow" target="_blank">https://github.com/SergeyTeplyakov/ObjectLayoutInspector</a></p>
<p>nuget 包地址:<a href="https://www.nuget.org/packages/ObjectLayoutInspector" rel="noopener nofollow" target="_blank">https://www.nuget.org/packages/ObjectLayoutInspector</a></p>
<div class="jb51code"><pre class="brush:csharp;">dotnet add package ObjectLayoutInspector --version 0.1.4</pre></div>
<p class="maodian"><a name="_label1"></a></p><h2>基本概念</h2>
<p>以下是理解结构体字段布局的几个关键点:</p>
<ul><li><strong>字段顺序</strong>:字段在结构体实例中的排列顺序,默认按声明顺序排列,但可以通过 <code>StructLayoutAttribute</code> 来控制。</li><li><strong>对齐(Alignment)</strong>:对齐需要分成三部分理解:<ul><li>字段的对齐要求(alignment requirement):指字段在内存中的地址必须是其对齐要求的倍数。对于基元类型(primitive types),对齐要求默认等于其大小,非基元类型的对齐要求取决于结构体中最大字段的对齐要求。</li><li>结构体实例的大小:必须是结构体对齐要求的整数倍。</li><li>结构体实例的起始地址:在 64 位系统中,数据的地址按 8 字节 对齐有利于提升 CPU 的访问效率,32 位系统中则为 4 字节对齐。</li><li><strong>填充(Padding)</strong>:为了满足对齐要求,runtime 可能会在结构体实例字段之间及末尾插入填充字节。这些填充字节不会被显式声明,但会影响字段在内存中的实际布局。</li></ul></li></ul>
<p class="maodian"><a name="_label2"></a></p><h2>结构体的默认字段布局</h2>
<p class="maodian"><a name="_lab2_2_0"></a></p><h3>对齐</h3>
<p>字段默认的对齐要求是类型的大小。例如,<code>int</code> 类型的字段需要在 4 字节对齐边界(alignment boundary)上,而 <code>double</code> 类型的字段需要在 8 字节对齐边界上。如果字段类型并非基元类型(primitive types),则对齐要求取决于结构体中最大字段的对齐要求。对齐要求为 2 的整数次幂,例如 1、2、4、8 等。<strong>最大对齐要求为 8 字节。</strong></p>
<p>注意:<code>decimal</code> 不属于基元类型,目前版本中由三个字段组成,实例大小为 16 字节,按 8 字节对齐。</p>
<div class="jb51code"><pre class="brush:csharp;">Type layout for 'Decimal'
Size: 16 bytes. Paddings: 0 bytes (%0 of empty space)
|===============================|
|   0-3: Int32 _flags (4 bytes) |
|-------------------------------|
|   4-7: UInt32 _hi32 (4 bytes) |
|-------------------------------|
|8-15: UInt64 _lo64 (8 bytes) |
|===============================|</pre></div>
<p>下面是一个简单的示例,展示了结构体字段的默认布局:</p>
<div class="jb51code"><pre class="brush:csharp;">using System.Runtime.CompilerServices;
var foo = new Foo();
var bar = new Bar();
var baz = new Baz();
unsafe
{
    PrintPointerHeader();
    PrintPointerDetails(&amp;foo);
    PrintPointerDetails(&amp;foo.a);
    PrintPointerDetails(&amp;foo.b);
    PrintPointerDetails(&amp;bar);
    PrintPointerDetails(&amp;bar.foo);
    PrintPointerDetails(&amp;bar.foo.a);
    PrintPointerDetails(&amp;bar.foo.b);
    fixed (Foo* bazFooPtr = &amp;baz.foo)
    {
      PrintPointerDetails(bazFooPtr);
      PrintPointerDetails(&amp;bazFooPtr-&gt;a);
      PrintPointerDetails(&amp;bazFooPtr-&gt;b);
    }
}
struct Foo
{
    public int a;
    public long b;
}
struct Bar
{
    public Foo foo;
}
class Baz
{
    public Foo foo;
}</pre></div>
<p>输出结果如下:</p>
<blockquote><p>| Expr &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;| Address &nbsp; &nbsp; &nbsp; &nbsp; | Size | AlignedBySize | Addr/Size &nbsp; &nbsp;|<br />| &amp;foo &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;| 6095528264 &nbsp; &nbsp; &nbsp;| 16 &nbsp; | False &nbsp; &nbsp; &nbsp; &nbsp; | 380970516.5 &nbsp;|<br />| &amp;foo.a &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;| 6095528264 &nbsp; &nbsp; &nbsp;| 4 &nbsp; &nbsp;| True &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;| 1523882066 &nbsp; |<br />| &amp;foo.b &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;| 6095528272 &nbsp; &nbsp; &nbsp;| 8 &nbsp; &nbsp;| True &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;| 761941034 &nbsp; &nbsp;|<br />| &amp;bar &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;| 6095528248 &nbsp; &nbsp; &nbsp;| 16 &nbsp; | False &nbsp; &nbsp; &nbsp; &nbsp; | 380970515.5 &nbsp;|<br />| &amp;bar.foo &nbsp; &nbsp; &nbsp; &nbsp;| 6095528248 &nbsp; &nbsp; &nbsp;| 16 &nbsp; | False &nbsp; &nbsp; &nbsp; &nbsp; | 380970515.5 &nbsp;|<br />| &amp;bar.foo.a &nbsp; &nbsp; &nbsp;| 6095528248 &nbsp; &nbsp; &nbsp;| 4 &nbsp; &nbsp;| True &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;| 1523882062 &nbsp; |<br />| &amp;bar.foo.b &nbsp; &nbsp; &nbsp;| 6095528256 &nbsp; &nbsp; &nbsp;| 8 &nbsp; &nbsp;| True &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;| 761941032 &nbsp; &nbsp;|<br />| bazFooPtr &nbsp; &nbsp; &nbsp; | 12885617264 &nbsp; &nbsp; | 16 &nbsp; | True &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;| 805351079 &nbsp; &nbsp;|<br />| &amp;bazFooPtr-&gt;a &nbsp; | 12885617264 &nbsp; &nbsp; | 4 &nbsp; &nbsp;| True &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;| 3221404316 &nbsp; |<br />| &amp;bazFooPtr-&gt;b &nbsp; | 12885617272 &nbsp; &nbsp; | 8 &nbsp; &nbsp;| True &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;| 1610702159 &nbsp; |</p></blockquote>
<p>首先看 <code>Foo</code> 结构体,它有两个字段 <code>a</code> 和 <code>b</code>,分别是 <code>int</code> 和 <code>long</code> 类型,对齐要求分别是 4 字节和 8 字节。</p>
<p>所以 <code>Foo</code> 实例在栈上的地址按照 8 字节 对齐(6095528264 / 8 = 761941033)。</p>
<p><code>a</code> 字段是 <code>foo</code> 的第一个字段,它的地址也就是 <code>foo</code> 的起始地址,自然也满足 <code>int</code> 的对齐要求(6095528264 / 4 = 1523882066)。</p>
<p><code>b</code> 字段是 <code>foo</code> 的第二个字段,它的地址为 6095528272,满足 <code>long</code> 的对齐要求(6095528272 / 8 = 761941032)。</p>
<p><code>Bar</code> 结构体包含一个 <code>Foo</code> 类型的字段 <code>foo</code>,它的对齐要求也是 8 字节(取最大字段 long 的对齐要求),所以 <code>bar</code> 的地址也是按照 8 字节对齐(6095528248 / 8 = 761941031)。<code>bar.foo.a</code> 和 <code>bar.foo.b</code> 的地址也满足各自的对齐要求。</p>
<p><code>Baz</code> 类包含一个 <code>Foo</code> 类型的字段 <code>foo</code>,由于 <code>Baz</code> 是引用类型,所以它的实例在堆上分配内存。<code>Baz</code> 的 <code>Foo</code> 类型字段也依旧需要满足 8 字节对齐要求(12885617264 / 8 = 1610702158)。</p>
<p class="maodian"><a name="_lab2_2_1"></a></p><h3>64 位系统与 32 位系统的对齐要求差异</h3>
<p>在 64 位系统中,结构体实例的起始地址默认按 8 字节对齐。</p>
<p>而在 32 位系统中,结构体实例的起始地址默认按 4 字节对齐。经笔者测试,CPU 为 intel 时 只按 4 字节对齐,CPU 为 AMD 时 如果结构体包含了 8 字节对齐的字段,则按 8 字节对齐,否则按 4 字节对齐。</p>
<p>首先在 64 位系统上运行下面的代码:</p>
<div class="jb51code"><pre class="brush:csharp;">using System.Runtime.CompilerServices;
using ObjectLayoutInspector;
unsafe
{
    var foo = new Foo();
    var bar = new Bar();
    // 方法 PrintPointerHeader 和 PrintPointerDetails 在前言部分已经定义
    PrintPointerHeader();
    PrintPointerDetails(&amp;foo.a);
    PrintPointerDetails(&amp;foo.b);
    PrintPointerDetails(&amp;foo.c);
    PrintPointerDetails(&amp;bar.d);
    PrintPointerDetails(&amp;bar.e);
    PrintPointerDetails(&amp;bar.f);
}
TypeLayout.PrintLayout&lt;Foo&gt;();
TypeLayout.PrintLayout&lt;Bar&gt;();
struct Foo
{
    public int a;
    public long b;
    public byte c;
}
struct Bar
{
    public int d;
    public int e;
    public byte f;
}</pre></div>
<p>输出结果如下:</p>
<blockquote><p>| Expr &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;| Address &nbsp; &nbsp; &nbsp; &nbsp; | Size | AlignedBySize | Addr/Size &nbsp; &nbsp;|<br />| &amp;foo.a &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;| 985964996520 &nbsp; &nbsp;| 4 &nbsp; &nbsp;| True &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;| 246491249130 |<br />| &amp;foo.b &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;| 985964996528 &nbsp; &nbsp;| 8 &nbsp; &nbsp;| True &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;| 123245624566 |<br />| &amp;foo.c &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;| 985964996536 &nbsp; &nbsp;| 1 &nbsp; &nbsp;| True &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;| 985964996536 |<br />| &amp;bar.d &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;| 985964996504 &nbsp; &nbsp;| 4 &nbsp; &nbsp;| True &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;| 246491249126 |<br />| &amp;bar.e &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;| 985964996508 &nbsp; &nbsp;| 4 &nbsp; &nbsp;| True &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;| 246491249127 |<br />| &amp;bar.f &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;| 985964996512 &nbsp; &nbsp;| 1 &nbsp; &nbsp;| True &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;| 985964996512 |<br />Type layout for &#39;Foo&#39;<br />Size: 24 bytes. Paddings: 11 bytes (%45 of empty space)<br />|==========================|<br />| &nbsp; 0-3: Int32 a (4 bytes) |<br />|--------------------------|<br />| &nbsp; 4-7: padding (4 bytes) |<br />|--------------------------|<br />| &nbsp;8-15: Int64 b (8 bytes) |<br />|--------------------------|<br />| &nbsp; &nbsp;16: Byte c (1 byte) &nbsp; |<br />|--------------------------|<br />| 17-23: padding (7 bytes) |<br />|==========================|</p>
<p><br />Type layout for &#39;Bar&#39;<br />Size: 12 bytes. Paddings: 3 bytes (%25 of empty space)<br />|==========================|<br />| &nbsp; 0-3: Int32 d (4 bytes) |<br />|--------------------------|<br />| &nbsp; 4-7: Int32 e (4 bytes) |<br />|--------------------------|<br />| &nbsp; &nbsp; 8: Byte f (1 byte) &nbsp; |<br />|--------------------------|<br />| &nbsp;9-11: padding (3 bytes) |<br />|==========================|</p></blockquote>
<p>可以看到,<code>Foo</code> 和 <code>Bar</code> 结构体的实例大小分别为 24 字节和 12 字节,且它们的起始地址都满足 8 字节对齐要求。</p>
<p>在 Windows 环境中,如果安装了 x86 版本的 .NET SDK,可以在 csproj 文件中添加以下属性来让项目运行在 32 位的环境中:</p>
<div class="jb51code"><pre class="brush:csharp;">&lt;PropertyGroup&gt;
    &lt;RuntimeIdentifier&gt;win-x86&lt;/RuntimeIdentifier&gt;
&lt;/PropertyGroup&gt;
</pre></div>
<p>下面是 intel CPU 的输出结果:</p>
<blockquote><p>| Expr &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;| Address &nbsp; &nbsp; &nbsp; &nbsp; | Size | AlignedBySize | Addr/Size &nbsp; &nbsp;|<br />| &amp;foo.a &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;| 43511772 &nbsp; &nbsp; &nbsp; &nbsp;| 4 &nbsp; &nbsp;| True &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;| 10877943 &nbsp; &nbsp; |<br />| &amp;foo.b &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;| 43511780 &nbsp; &nbsp; &nbsp; &nbsp;| 8 &nbsp; &nbsp;| False &nbsp; &nbsp; &nbsp; &nbsp; | 5438972.5 &nbsp; &nbsp;|<br />| &amp;foo.c &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;| 43511788 &nbsp; &nbsp; &nbsp; &nbsp;| 1 &nbsp; &nbsp;| True &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;| 43511788 &nbsp; &nbsp; |<br />| &amp;bar.d &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;| 43511760 &nbsp; &nbsp; &nbsp; &nbsp;| 4 &nbsp; &nbsp;| True &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;| 10877940 &nbsp; &nbsp; |<br />| &amp;bar.e &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;| 43511764 &nbsp; &nbsp; &nbsp; &nbsp;| 4 &nbsp; &nbsp;| True &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;| 10877941 &nbsp; &nbsp; |<br />| &amp;bar.f &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;| 43511768 &nbsp; &nbsp; &nbsp; &nbsp;| 1 &nbsp; &nbsp;| True &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;| 43511768 &nbsp; &nbsp; |<br />Type layout for &#39;Foo&#39;<br />Size: 24 bytes. Paddings: 11 bytes (%45 of empty space)<br />|==========================|<br />| &nbsp; 0-3: Int32 a (4 bytes) |<br />|--------------------------|<br />| &nbsp; 4-7: padding (4 bytes) |<br />|--------------------------|<br />| &nbsp;8-15: Int64 b (8 bytes) |<br />|--------------------------|<br />| &nbsp; &nbsp;16: Byte c (1 byte) &nbsp; |<br />|--------------------------|<br />| 17-23: padding (7 bytes) |<br />|==========================|</p>
<p><br />Type layout for &#39;Bar&#39;<br />Size: 12 bytes. Paddings: 3 bytes (%25 of empty space)<br />|==========================|<br />| &nbsp; 0-3: Int32 d (4 bytes) |<br />|--------------------------|<br />| &nbsp; 4-7: Int32 e (4 bytes) |<br />|--------------------------|<br />| &nbsp; &nbsp; 8: Byte f (1 byte) &nbsp; |<br />|--------------------------|<br />| &nbsp;9-11: padding (3 bytes) |<br />|==========================|</p></blockquote>
<p><code>Foo</code> 和 <code>Bar</code> 结构体的起始地址和字段地址都只满足 4 字节对齐要求(43511772 / 4 = 10877943),而不是 8 字节对齐要求。</p>
<p>下面是 AMD CPU 的输出结果:</p>
<p>运行上述代码,输出结果如下:</p>
<blockquote><p>```bash<br />| Expr &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;| Address &nbsp; &nbsp; &nbsp; &nbsp; | Size | AlignedBySize | Addr/Size &nbsp; &nbsp;|<br />| &amp;foo.a &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;| 47706560 &nbsp; &nbsp; &nbsp; &nbsp;| 4 &nbsp; &nbsp;| True &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;| 11926640 &nbsp; &nbsp; |<br />| &amp;foo.b &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;| 47706568 &nbsp; &nbsp; &nbsp; &nbsp;| 8 &nbsp; &nbsp;| True &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;| 5963321 &nbsp; &nbsp; &nbsp;|<br />| &amp;foo.c &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;| 47706576 &nbsp; &nbsp; &nbsp; &nbsp;| 1 &nbsp; &nbsp;| True &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;| 47706576 &nbsp; &nbsp; |<br />| &amp;bar.d &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;| 47706548 &nbsp; &nbsp; &nbsp; &nbsp;| 4 &nbsp; &nbsp;| True &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;| 11926637 &nbsp; &nbsp; |<br />| &amp;bar.e &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;| 47706552 &nbsp; &nbsp; &nbsp; &nbsp;| 4 &nbsp; &nbsp;| True &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;| 11926638 &nbsp; &nbsp; |<br />| &amp;bar.f &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;| 47706556 &nbsp; &nbsp; &nbsp; &nbsp;| 1 &nbsp; &nbsp;| True &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;| 47706556 &nbsp; &nbsp; |<br />Type layout for &#39;Foo&#39;<br />Size: 24 bytes. Paddings: 11 bytes (%45 of empty space)<br />|==========================|<br />| &nbsp; 0-3: Int32 a (4 bytes) |<br />|--------------------------|<br />| &nbsp; 4-7: padding (4 bytes) |<br />|--------------------------|<br />| &nbsp;8-15: Int64 b (8 bytes) |<br />|--------------------------|<br />| &nbsp; &nbsp;16: Byte c (1 byte) &nbsp; |<br />|--------------------------|<br />| 17-23: padding (7 bytes) |<br />|==========================|</p>
<p><br />Type layout for &#39;Bar&#39;<br />Size: 12 bytes. Paddings: 3 bytes (%25 of empty space)<br />|==========================|<br />| &nbsp; 0-3: Int32 d (4 bytes) |<br />|--------------------------|<br />| &nbsp; 4-7: Int32 e (4 bytes) |<br />|--------------------------|<br />| &nbsp; &nbsp; 8: Byte f (1 byte) &nbsp; |<br />|--------------------------|<br />| &nbsp;9-11: padding (3 bytes) |<br />|==========================|</p></blockquote>
<p><code>Foo</code> 的起始地址仍然满足 8 字节对齐要求,但 <code>Bar</code> 的起始地址不再满足 8 字节对齐要求(47706548 / 8 = 5963318.5),而是满足 4 字节对齐要求(47706548 / 4 = 11926637)。</p>
<p class="maodian"><a name="_lab2_2_2"></a></p><h3>默认字段布局中 对齐要求 与 偏移量 的关系</h3>
<p>偏移量(offset)是指字段相对于结构体实例起始地址的距离,决定了字段在内存中的位置。</p>
<p><strong>偏移量的值取决于对齐要求和字段的顺序,会在未被顺序在前的字段占用的内存空间中取对齐要求的最小整数倍。</strong></p>
<p>下面几个设计确保了不管结构体实例的起始地址如何,任意一个字段只要给定一个满足对齐要求的偏移量,就可以满足该字段的对齐要求:</p>
<ul><li>对齐要求总是 2 的整数次幂。</li><li>实例的起始地址(按 8 字节 对齐)总是满足最大字段的对齐要求。</li><li>偏移量的值是对齐要求的整数倍</li></ul>
<p>下面做一个简单的推导来帮助读者理解:</p>
<p>假设结构体中最大字段的对齐要求为 2^m(m 为 &lt;= 8 的非负整数),则 runtime 会保证结构体实例的起始地址也是 2^m 的整数倍,可记作 2^m * k(k为非负整数)。</p>
<p>若某字段的对齐要求为 2^n(n&le;m),其偏移量必为 2^n 的整数倍,记为 2^n * f(f为非负整数)。</p>
<p>则该字段实际地址为:</p>
<p><code>结构体起始地址 + 字段偏移量 = (2^m * k) + (2^n * f)</code></p>
<p>由于 2^m 必定可以被 2^n 整除(因为 n&le;m),所以无论 k 和 f 取何值,上述字段地址总能被 2^n 整除。这就保证了该字段的地址总是满足其对齐要求。</p>
<p>因此,只要给每个字段的 偏移量 选择其 对齐要求 的整数倍,就能保证结构体任何实例、任意字段的地址都天然对齐,而无需依赖结构体起始地址的额外信息。</p>
<div class="jb51code"><pre class="brush:csharp;">unsafe
{
    var foo = new Foo();
    var addr = (ulong)&amp;foo;
    Console.WriteLine($"a offset: {(ulong)&amp;foo.a - addr}");
    Console.WriteLine($"b offset: {(ulong)&amp;foo.b - addr}");
    Console.WriteLine($"c offset: {(ulong)&amp;foo.c - addr}");
}
struct Foo
{
    public int a;
    public long b;
    public byte c;
}</pre></div>
<p>输出结果如下:</p>
<blockquote><p>a offset: 0<br />b offset: 8<br />c offset: 16</p></blockquote>
<p class="maodian"><a name="_label3"></a></p><h2>填充</h2>
<p>填充(Padding)分为两部分:</p>
<ul><li><strong>字段之间的填充</strong>:为了满足对齐要求,.NET 可能会在字段之间插入填充字节。字段之间的填充由字段的偏移量决定。</li><li><strong>结构体末尾的填充</strong>:为了确保结构体的大小是最大字段对齐要求的倍数,.NET 可能会在结构体末尾添加填充字节。末尾填充保证了数组中连续的结构体实例在内存中也满足对齐要求。</li></ul>
<p>借助 <code>ObjectLayoutInspector</code> 库,我们可以观察到结构体的内存布局,包括字段之间的填充和结构体末尾的填充。</p>
<div class="jb51code"><pre class="brush:csharp;">using ObjectLayoutInspector;
TypeLayout.PrintLayout&lt;Foo&gt;();
TypeLayout.PrintLayout&lt;Bar&gt;();
struct Foo
{
    public int a;
    public long b;
    public byte c;
}
struct Bar
{
    public byte c;
    public int a;
    public long b;
}</pre></div>
<p>输出结果如下:</p>
<blockquote><p>Type layout for &#39;Foo&#39;<br />Size: 24 bytes. Paddings: 11 bytes (%45 of empty space)<br />|==========================|<br />| &nbsp; 0-3: Int32 a (4 bytes) |<br />|--------------------------|<br />| &nbsp; 4-7: padding (4 bytes) |<br />|--------------------------|<br />| &nbsp;8-15: Int64 b (8 bytes) |<br />|--------------------------|<br />| &nbsp; &nbsp;16: Byte c (1 byte) &nbsp; |<br />|--------------------------|<br />| 17-23: padding (7 bytes) |<br />|==========================|</p>
<p><br />Type layout for &#39;Bar&#39;<br />Size: 16 bytes. Paddings: 3 bytes (%18 of empty space)<br />|==========================|<br />| &nbsp; &nbsp; 0: Byte c (1 byte) &nbsp; |<br />|--------------------------|<br />| &nbsp; 1-3: padding (3 bytes) |<br />|--------------------------|<br />| &nbsp; 4-7: Int32 a (4 bytes) |<br />|--------------------------|<br />| &nbsp;8-15: Int64 b (8 bytes) |<br />|==========================|</p></blockquote>
<p><code>Foo</code> 和 <code>Bar</code> 虽然包含了相同类型的字段,但由于字段的顺序不同,导致它们的内存布局和填充字节数量也不同。<code>Foo</code> 需要在在末尾添加 7 字节的填充才能满足其大小是最大字段对齐要求的倍数。</p>
<p class="maodian"><a name="_label4"></a></p><h2>包含引用类型字段的结构体的默认字段布局</h2>
<p>如果结构体包含引用类型字段,则该结构体的默认布局为 <code>LayoutKind.Auto</code>。</p>
<div class="jb51code"><pre class="brush:csharp;">using ObjectLayoutInspector;
TypeLayout.PrintLayout&lt;Foo&gt;();
struct Foo
{
    public int a;
    public string b;
    public byte c;
}</pre></div>
<div class="jb51code"><pre class="brush:csharp;">Type layout for 'Foo'
Size: 16 bytes. Paddings: 3 bytes (%18 of empty space)
|===========================|
|   0-7: String b (8 bytes) |
|---------------------------|
|8-11: Int32 a (4 bytes)|
|---------------------------|
|    12: Byte c (1 byte)    |
|---------------------------|
| 13-15: padding (3 bytes)|
|===========================|
</pre></div>
<p class="maodian"><a name="_label5"></a></p><h2>用StructLayoutAttribute控制字段布局</h2>
<p>在某些情况下,我们可能需要控制结构体字段的内存布局,以满足特定的性能要求或与非托管代码交互。可以使用 <code>StructLayoutAttribute</code> 特性来控制结构体的内存布局。</p>
<p><code>StructLayoutAttribute</code> 有两个重要的属性:</p>
<ul><li><code>LayoutKind</code>:指定结构体的布局方式,可以是 <code>Sequential</code>(按声明顺序排列)、<code>Explicit</code>(显式指定字段偏移量)或 <code>Auto</code>(自动布局)。</li><li><code>Pack</code>:指定结构体及其字段的对齐要求,其值必须为 0、1、2、4、8、16、32、64 或 128,否则无法编译成功,默认值为 0。** 指定 <code>Pack</code> &gt; 8 时, 等效于 <code>Pack = 8</code>,因为目前版本没有任何类型的对齐要求超过 8 字节。**</li></ul>
<p><code>Pack</code> 属性在 <code>LayoutKind.Auto</code> 布局中无效。在 <code>LayoutKind.Sequential</code> 布局中,<code>Pack</code> 属性用于指定字段的对齐要求及结构体实例的对齐要求;在 <code>LayoutKind.Explicit</code> 布局中,<code>Pack</code> 属性用于结构体的对齐要求,会影响结构体实例的末尾填充。</p>
<p class="maodian"><a name="_label6"></a></p><h2>LayoutKind.Sequential</h2>
<p class="maodian"><a name="_lab2_6_3"></a></p><h3>Pack 为 0 时等于默认布局</h3>
<div class="jb51code"><pre class="brush:csharp;">using System.Runtime.InteropServices;
using ObjectLayoutInspector;
TypeLayout.PrintLayout&lt;Foo&gt;();

struct Foo
{
    public int a;
    public long b;
    public byte c;
}</pre></div>
<div class="jb51code"><pre class="brush:csharp;">Type layout for 'Foo'
Size: 24 bytes. Paddings: 11 bytes (%45 of empty space)
|==========================|
|   0-3: Int32 a (4 bytes) |
|--------------------------|
|   4-7: padding (4 bytes) |
|--------------------------|
|8-15: Int64 b (8 bytes) |
|--------------------------|
|    16: Byte c (1 byte)   |
|--------------------------|
| 17-23: padding (7 bytes) |
|==========================|
</pre></div>
<p class="maodian"><a name="_lab2_6_4"></a></p><h3>Pack 不为 0 时,取 Pack 和 字段类型大小 的较小值</h3>
<p><code>Pack</code> 设置为 4 时,<code>int</code> 和 <code>long</code> 字段的对齐要求都将被设置为 4 字节,而 <code>byte</code> 字段的对齐要求仍然是 1 字节。结构体的对齐要求是 4 字节。</p>
<div class="jb51code"><pre class="brush:csharp;">using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using ObjectLayoutInspector;
{
    var foo = new Foo();
    // 方法 PrintPointerHeader 和 PrintPointerDetails 在前言部分已经定义
    PrintPointerHeader();
    PrintPointerDetails(&amp;foo.a);
    PrintPointerDetails(&amp;foo.b);
    PrintPointerDetails(&amp;foo.c);
}
TypeLayout.PrintLayout&lt;Foo&gt;();

struct Foo
{
    public int a;
    public long b;
    public byte c;
}</pre></div>
<div class="jb51code"><pre class="brush:csharp;">| Expr            | Address         | Size | AlignedBySize | Addr/Size    |
| &amp;foo.a          | 782597876240    | 4    | True          | 195649469060 |
| &amp;foo.b          | 782597876244    | 8    | False         | 97824734530.5 |
| &amp;foo.c          | 782597876252    | 1    | True          | 782597876252 |
Type layout for 'Foo'
Size: 16 bytes. Paddings: 3 bytes (%18 of empty space)
|==========================|
|   0-3: Int32 a (4 bytes) |
|--------------------------|
|4-11: Int64 b (8 bytes) |
|--------------------------|
|    12: Byte c (1 byte)   |
|--------------------------|
| 13-15: padding (3 bytes) |
|==========================|
</pre></div>
<p>结构体实例的起始地址按 8 字节 对齐(782597876240 / 8 = 97824734530)。但其大小取满足 4 字节对齐要求的最小整数倍 16 字节( 末尾字段 c 的偏移量为 12,最小只能取到 16),并在末尾添加 3 字节的填充。</p>
<p class="maodian"><a name="_lab2_6_5"></a></p><h3>Pack 设置为 1 时,会形成密集的字段布局</h3>
<p>当 <code>Pack</code> 设置为 1 时,所有字段的对齐要求都将被设置为 1 字节,这意味着结构体实例将按照 1 字节对齐。此时,结构体实例的字段将紧密排列,不会有额外的填充字节。</p>
<div class="jb51code"><pre class="brush:csharp;">using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using ObjectLayoutInspector;
var foo = new Foo
{
    a = 1,
    b = 2,
    c = 3
};
unsafe
{
    // 方法 PrintPointerHeader 和 PrintPointerDetails 在前言部分已经定义
    PrintPointerHeader();
    PrintPointerDetails(&amp;foo.a);
    PrintPointerDetails(&amp;foo.b);
    PrintPointerDetails(&amp;foo.c);
}
TypeLayout.PrintLayout&lt;Foo&gt;();

struct Foo
{
    public int a;
    public long b;
    public byte c;
}</pre></div>
<div class="jb51code"><pre class="brush:csharp;">| Expr            | Address         | Size | AlignedBySize | Addr/Size    |
| &amp;foo.a          | 302463314288    | 4    | True          | 75615828572|
| &amp;foo.b          | 302463314292    | 8    | False         | 37807914286.5 |
| &amp;foo.c          | 302463314300    | 1    | True          | 302463314300 |
Type layout for 'Foo'
Size: 13 bytes. Paddings: 0 bytes (%0 of empty space)
|==========================|
|   0-3: Int32 a (4 bytes) |
|--------------------------|
|4-11: Int64 b (8 bytes) |
|--------------------------|
|    12: Byte c (1 byte)   |
|==========================|
</pre></div>
<p>起始地址为 8 的倍数(302463314288 / 8 = 37807914286),但结构体实例的大小变为 13 字节,没有末尾填充。</p>
<p class="maodian"><a name="_lab2_6_6"></a></p><h3>Pack 不为 0 的结构体作为其他结构体字段时</h3>
<p>如果外层的结构体采用默认字段布局则,则其实例的起始地址取决嵌套结构体的最大字段默认对齐要求,其实例大小取决该结构体的最大字段对齐要求。</p>
<div class="jb51code"><pre class="brush:csharp;">using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using ObjectLayoutInspector;
unsafe
{
    PrintPointerHeader();
    PrintPointerDetails(&amp;bar.foo.a);
    PrintPointerDetails(&amp;bar.foo.b);
    PrintPointerDetails(&amp;bar.foo.c);
    PrintPointerDetails(&amp;bar.d);
}
TypeLayout.PrintLayout&lt;Bar&gt;();

struct Foo
{
    public int a;
    public long b;
    public byte c;
}
struct Bar
{
    public Foo foo;
    public int d;
}</pre></div>
<div class="jb51code"><pre class="brush:csharp;">| Expr            | Address         | Size | AlignedBySize | Addr/Size    |
| &amp;bar.foo.a      | 724703897336    | 4    | True          | 181175974334 |
| &amp;bar.foo.b      | 724703897340    | 8    | False         | 90587987167.5 |
| &amp;bar.foo.c      | 724703897348    | 1    | True          | 724703897348 |
| &amp;bar.d          | 724703897352    | 4    | True          | 181175974338 |
Type layout for 'Bar'
Size: 20 bytes. Paddings: 3 bytes (%15 of empty space)
|==============================|
|0-12: Foo foo (13 bytes)    |
| |==========================| |
| |   0-3: Int32 a (4 bytes) | |
| |--------------------------| |
| |4-11: Int64 b (8 bytes) | |
| |--------------------------| |
| |    12: Byte c (1 byte)   | |
| |==========================| |
|------------------------------|
| 13-15: padding (3 bytes)   |
|------------------------------|
| 16-19: Int32 d (4 bytes)   |
|==============================|
</pre></div>
<p>在上面的例子中,<code>Bar</code> 结构体包含一个 <code>Foo</code> 类型的字段 <code>foo</code>。</p>
<p><code>Bar</code> 的实例起始地址也满足 8 字节对齐要求(724703897336 / 8 = 90587987167)。</p>
<p><code>foo</code> 的对齐要求为 1 字节, <code>d</code> 的对齐要求为 4 字节,所以 <code>Bar</code> 的实例大小为 20 字节(4 的整数倍),并在<code>foo</code> 和 <code>d</code> 之间添加了 3 字节的填充。</p>
<p class="maodian"><a name="_label7"></a></p><h2>LayoutKind.Explicit</h2>
<p class="maodian"><a name="_lab2_7_7"></a></p><h3>Pack 为 0 时,结构体按照最大字段默认对齐要求对齐</h3>
<p>在 <code>Explicit</code> 布局中,我们需要显式指定每个字段的偏移量。使用 <code>FieldOffsetAttribute</code> 来指定字段的偏移量。此时偏移量可以是任意值,甚至允许重叠字段。</p>
<p>此时虽然字段地址可能由于是任意值而不满足对齐要求,但结构体实例的起始地址依旧按 8 字节 对齐,且结构体实例的大小是最大字段对齐要求的整数倍。</p>
<div class="jb51code"><pre class="brush:csharp;">using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using ObjectLayoutInspector;
var foo = new Foo
{
    a = 1,
    b = 2,
    c = 3
};
unsafe
{
    // 方法 PrintPointerHeader 和 PrintPointerDetails 在前言部分已经定义
    PrintPointerHeader();
    PrintPointerDetails(&amp;foo.a);
    PrintPointerDetails(&amp;foo.b);
    PrintPointerDetails(&amp;foo.c);
}
TypeLayout.PrintLayout&lt;Foo&gt;();

struct Foo
{
   
    public int a;
   
    public long b;
   
    public byte c;
}</pre></div>
<div class="jb51code"><pre class="brush:csharp;">| Expr            | Address         | Size | AlignedBySize | Addr/Size    |
| &amp;foo.a          | 6095151432      | 4    | True          | 1523787858   |
| &amp;foo.b          | 6095151435      | 8    | False         | 761893929.38 |
| &amp;foo.c          | 6095151443      | 1    | True          | 6095151443   |
Type layout for 'Foo'
Size: 16 bytes. Paddings: 4 bytes (%25 of empty space)
|==========================|
|   0-3: Int32 a (4 bytes) |
|--------------------------|
|3-10: Int64 b (8 bytes) |
|--------------------------|
|    11: Byte c (1 byte)   |
|--------------------------|
| 12-15: padding (4 bytes) |
|==========================|
</pre></div>
<p>上面例子中,<code>Foo</code> 结构体的字段 <code>a</code>、<code>b</code> 和 <code>c</code> 的偏移量分别为 0、3 和 11。可以看到,虽然字段的地址不再满足对齐要求,但结构体实例的起始地址仍然按 8 字节 对齐(6095151432 / 8 = 761893929),且结构体实例的大小为 16 字节(最大字段对齐要求的整数倍),末尾添加了 4 字节的填充。</p>
<p>如果将 <code>c</code> 字段的偏移量改为 16,则结构体实例的大小将变为 24 字节,并且会在末尾添加 7 字节的填充。</p>
<div class="jb51code"><pre class="brush:csharp;">using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using ObjectLayoutInspector;
var foo = new Foo
{
    a = 1,
    b = 2,
    c = 3
};
unsafe
{
    PrintPointerHeader();
    PrintPointerDetails(&amp;foo.a);
    PrintPointerDetails(&amp;foo.b);
    PrintPointerDetails(&amp;foo.c);
}
TypeLayout.PrintLayout&lt;Foo&gt;();</pre></div>
<div class="jb51code"><pre class="brush:csharp;">| Expr            | Address         | Size | AlignedBySize | Addr/Size    |
| &amp;foo.a          | 6166536512      | 4    | True          | 1541634128   |
| &amp;foo.b          | 6166536515      | 8    | False         | 770817064.38 |
| &amp;foo.c          | 6166536528      | 1    | True          | 6166536528   |
Type layout for 'Foo'
Size: 24 bytes. Paddings: 12 bytes (%50 of empty space)
|==========================|
|   0-3: Int32 a (4 bytes) |
|--------------------------|
|3-10: Int64 b (8 bytes) |
|--------------------------|
| 11-15: padding (5 bytes) |
|--------------------------|
|    16: Byte c (1 byte)   |
|--------------------------|
| 17-23: padding (7 bytes) |
|==========================|
</pre></div>
<p class="maodian"><a name="_lab2_7_8"></a></p><h3>Pack 不为 0 时,结构体实例按照 Pack 与 最大字段对齐要求 的较小值对齐</h3>
<p>在 <code>Explicit</code> 布局中,如果设置了 <code>Pack</code> 属性且不为 0,则结构体实例将按照 <code>Pack</code> 的值对齐。字段的偏移量仍然可以是任意值,但结构体实例的大小将受到 <code>Pack</code> 属性的影响。</p>
<div class="jb51code"><pre class="brush:csharp;">var foo = new Foo
{
    a = 1,
    b = 2,
    c = 3
};
unsafe
{
    PrintPointerHeader();
    PrintPointerDetails(&amp;foo.a);
    PrintPointerDetails(&amp;foo.b);
    PrintPointerDetails(&amp;foo.c);
}
TypeLayout.PrintLayout&lt;Foo&gt;();

struct Foo
{
   
    public int a;
   
    public long b;
   
    public byte c;
}</pre></div>
<div class="jb51code"><pre class="brush:csharp;">| Expr            | Address         | Size | AlignedBySize | Addr/Size    |
| &amp;foo.a          | 6122676544      | 4    | True          | 1530669136   |
| &amp;foo.b          | 6122676549      | 8    | False         | 765334568.63 |
| &amp;foo.c          | 6122676560      | 1    | True          | 6122676560   |
Type layout for 'Foo'
Size: 20 bytes. Paddings: 7 bytes (%35 of empty space)
|==========================|
|   0-3: Int32 a (4 bytes) |
|--------------------------|
|   4: padding (1 byte)|
|--------------------------|
|5-12: Int64 b (8 bytes) |
|--------------------------|
| 13-15: padding (3 bytes) |
|--------------------------|
|    16: Byte c (1 byte)   |
|--------------------------|
| 17-19: padding (3 bytes) |
|==========================|
</pre></div>
<p>在上面的例子中,由于 <code>Pack</code> 属性设置为 4,与 long 类型的 8 字节 比较则结构体实例应按照 4 字节 对齐。因为 <code>c</code> 的偏移量为 16,所以 <code>Foo</code> 的大小在取值此时符合条件的 4 的最小整数倍后变为 20 字节,并在末尾添加了 3 字节 的填充。</p>
<p>改成 <code>Pack = 128</code> 后,结构体实例的大小按照最大字段默认对齐要求 8 字节 对齐。</p>
<div class="jb51code"><pre class="brush:csharp;">var foo = new Foo
{
    a = 1,
    b = 2,
    c = 3
};
unsafe
{
    PrintPointerHeader();
    PrintPointerDetails(&amp;foo.a);
    PrintPointerDetails(&amp;foo.b);
    PrintPointerDetails(&amp;foo.c);
}
TypeLayout.PrintLayout&lt;Foo&gt;();

struct Foo
{
   
    public int a;
   
    public long b;
   
    public byte c;
}</pre></div>
<div class="jb51code"><pre class="brush:csharp;">| Expr            | Address         | Size | AlignedBySize | Addr/Size    |
| &amp;foo.a          | 6104211776      | 4    | True          | 1526052944   |
| &amp;foo.b          | 6104211781      | 8    | False         | 763026472.63 |
| &amp;foo.c          | 6104211792      | 1    | True          | 6104211792   |
Type layout for 'Foo'
Size: 24 bytes. Paddings: 11 bytes (%45 of empty space)
|==========================|
|   0-3: Int32 a (4 bytes) |
|--------------------------|
|   4: padding (1 byte)|
|--------------------------|
|5-12: Int64 b (8 bytes) |
|--------------------------|
| 13-15: padding (3 bytes) |
|--------------------------|
|    16: Byte c (1 byte)   |
|--------------------------|
| 17-23: padding (7 bytes) |
|==========================|
</pre></div>
<p class="maodian"><a name="_lab2_7_9"></a></p><h3>将 Pack 属性设置为 1 可以消除结构体实例的末尾填充</h3>
<div class="jb51code"><pre class="brush:csharp;">using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using ObjectLayoutInspector;
var foo = new Foo
{
    a = 1,
    b = 2,
    c = 3
};
unsafe
{
    PrintPointerHeader();
    PrintPointerDetails(&amp;foo.a);
    PrintPointerDetails(&amp;foo.b);
    PrintPointerDetails(&amp;foo.c);
}
TypeLayout.PrintLayout&lt;Foo&gt;();

struct Foo
{
   
    public int a;
   
    public long b;
   
    public byte c;
}</pre></div>
<div class="jb51code"><pre class="brush:csharp;">| Expr            | Address         | Size | AlignedBySize | Addr/Size    |
| &amp;foo.a          | 468685679112    | 4    | True          | 117171419778 |
| &amp;foo.b          | 468685679117    | 8    | False         | 58585709889.63 |
| &amp;foo.c          | 468685679128    | 1    | True          | 468685679128 |
Type layout for 'Foo'
Size: 17 bytes. Paddings: 4 bytes (%23 of empty space)
|==========================|
|   0-3: Int32 a (4 bytes) |
|--------------------------|
|   4: padding (1 byte)|
|--------------------------|
|5-12: Int64 b (8 bytes) |
|--------------------------|
| 13-15: padding (3 bytes) |
|--------------------------|
|    16: Byte c (1 byte)   |
|==========================|
</pre></div>
<p>此时实例的起始地址仍然按 8 字节 对齐(468685679112 / 8 = 58585709889),但实例的大小则是 17 字节,末尾填充为 0 字节。</p>
<p class="maodian"><a name="_lab2_7_10"></a></p><h3>Pack 属性不为 0 的结构体作为其他结构体字段时</h3>
<div class="jb51code"><pre class="brush:csharp;">using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using ObjectLayoutInspector;
var bar = new Bar
{
    foo = new Foo(),
    d = 4
};
unsafe
{
    PrintPointerHeader();
    PrintPointerDetails(&amp;bar.foo.a);
    PrintPointerDetails(&amp;bar.foo.b);
    PrintPointerDetails(&amp;bar.foo.c);
    PrintPointerDetails(&amp;bar.d);
}
TypeLayout.PrintLayout&lt;Bar&gt;();

struct Foo
{
   
    public int a;
   
    public long b;
   
    public byte c;
}
struct Bar
{
    public Foo foo;
    public int d;
}</pre></div>
<div class="jb51code"><pre class="brush:csharp;">| Expr            | Address         | Size | AlignedBySize | Addr/Size    |
| &amp;bar.foo.a      | 967090628200    | 4    | True          | 241772657050 |
| &amp;bar.foo.b      | 967090628205    | 8    | False         | 120886328525.63 |
| &amp;bar.foo.c      | 967090628216    | 1    | True          | 967090628216 |
| &amp;bar.d          | 967090628220    | 4    | True          | 241772657055 |
Type layout for 'Bar'
Size: 24 bytes. Paddings: 7 bytes (%29 of empty space)
|==============================|
|0-16: Foo foo (17 bytes)    |
| |==========================| |
| |   0-3: Int32 a (4 bytes) | |
| |--------------------------| |
| |   4: padding (1 byte)| |
| |--------------------------| |
| |5-12: Int64 b (8 bytes) | |
| |--------------------------| |
| | 13-15: padding (3 bytes) | |
| |--------------------------| |
| |    16: Byte c (1 byte)   | |
| |==========================| |
|------------------------------|
| 17-19: padding (3 bytes)   |
|------------------------------|
| 20-23: Int32 d (4 bytes)   |
|==============================|
</pre></div>
<p>在上面的例子中,<code>Bar</code> 结构体包含一个 <code>Foo</code> 类型的字段 <code>foo</code>,由于 <code>Foo</code> 的最大字段对齐要求为 8 字节,所以 <code>Bar</code> 的实例起始地址也满足 8 字节对齐要求(967090628200 / 8 = 120886328525)。</p>
<p><code>foo</code> 的对齐要求为 1 字节, <code>d</code> 的对齐要求为 4 字节,所以 <code>Bar</code> 的实例大小为 24 字节(4 的整数倍),并在<code>foo</code> 和 <code>d</code> 之间添加了 3 字节的填充。</p>
<p class="maodian"><a name="_label8"></a></p><h2>LayoutKind.Auto</h2>
<p>使用 <code>LayoutKind.Auto</code> 时,runtime 将根据字段的类型和声明顺序自动确定字段的布局,会调整实例字段的排列顺序和对齐要求,以优化内存布局和性能。</p>
<p><code>LayoutKind.Auto</code> 也是引用类型实例字段的默认布局方式。</p>
<div class="jb51code"><pre class="brush:csharp;">using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using ObjectLayoutInspector;
var foo = new Foo
{
    a = 1,
    b = 2,
    c = 3
};
unsafe
{
    PrintPointerHeader();
    PrintPointerDetails(&amp;foo.a);
    PrintPointerDetails(&amp;foo.b);
    PrintPointerDetails(&amp;foo.c);
}
TypeLayout.PrintLayout&lt;Foo&gt;();

struct Foo
{
    public int a;
    public long b;
    public byte c;
}</pre></div>
<div class="jb51code"><pre class="brush:csharp;">| Expr            | Address         | Size | AlignedBySize | Addr/Size    |
| &amp;foo.a          | 6166815056      | 4    | True          | 1541703764   |
| &amp;foo.b          | 6166815048      | 8    | True          | 770851881    |
| &amp;foo.c          | 6166815060      | 1    | True          | 6166815060   |
Type layout for 'Foo'
Size: 16 bytes. Paddings: 3 bytes (%18 of empty space)
|==========================|
|   0-7: Int64 b (8 bytes) |
|--------------------------|
|8-11: Int32 a (4 bytes) |
|--------------------------|
|    12: Byte c (1 byte)   |
|--------------------------|
| 13-15: padding (3 bytes) |
|==========================|
</pre></div>
<p>上面例子中,<code>Foo</code> 结构体的字段 <code>b</code> 被放在了前面,各字段都按照其类型大小进行了对齐,相较于默认布局,<code>Foo</code> 结构体的内存布局更加紧凑,减少了填充字节的数量。</p>
<p>等效于于下面的结构体定义</p>
<div class="jb51code"><pre class="brush:csharp;">
struct Foo
{
    public long b;
    public int a;
    public byte c;
}
</pre></div>
<p class="maodian"><a name="_label9"></a></p><h2>作为数组元素时的结构体实例</h2>
<p class="maodian"><a name="_lab2_9_11"></a></p><h3>默认字段布局</h3>
<p>默认布局的结构体实例在数组中也会按照最大字段对齐要求进行对齐。每个结构体实例的起始地址都是该结构体最大字段对齐要求的整数倍。</p>
<p>因此默认布局下,数组中的每个结构体的字段都是满足对齐要求的。</p>
<div class="jb51code"><pre class="brush:csharp;">using System.Runtime.CompilerServices;
unsafe
{
    // 读者也可以替换成堆上分配的数组来查看运行结果
    var arr = stackalloc Foo[] { new Foo(), new Foo() };
    PrintPointerHeader();
    PrintPointerDetails(&amp;arr.a);
    PrintPointerDetails(&amp;arr.b);
    PrintPointerDetails(&amp;arr.c);
    PrintPointerDetails(&amp;arr.a);
    PrintPointerDetails(&amp;arr.b);
    PrintPointerDetails(&amp;arr.c);
}
struct Foo
{
    public int a;
    public long b;
    public byte c;
}</pre></div>
<div class="jb51code"><pre class="brush:csharp;">| Expr            | Address         | Size | AlignedBySize | Addr/Size    |
| &amp;arr.a       | 1029625933216   | 4    | True          | 257406483304 |
| &amp;arr.b       | 1029625933224   | 8    | True          | 128703241653 |
| &amp;arr.c       | 1029625933232   | 1    | True          | 1029625933232 |
| &amp;arr.a       | 1029625933240   | 4    | True          | 257406483310 |
| &amp;arr.b       | 1029625933248   | 8    | True          | 128703241656 |
| &amp;arr.c       | 1029625933256   | 1    | True          | 1029625933256 |
</pre></div>
<p class="maodian"><a name="_lab2_9_12"></a></p><h3>非默认字段布局</h3>
<p>因为数组中结构体实例是连续存储的,如果结构体实例的字段布局进行了非默认的调整,则可能导致第二个开始的构体实例完全不满足对齐要求(包括实例的起始地址和字段地址)。</p>
<div class="jb51code"><pre class="brush:csharp;">using System.Runtime.CompilerServices;
unsafe
{
    // 读者也可以替换成堆上分配的数组来查看运行结果
    var arr = stackalloc Foo[] { new Foo(), new Foo() };
    PrintPointerHeader();
    PrintPointerDetails(&amp;arr.a);
    PrintPointerDetails(&amp;arr.b);
    PrintPointerDetails(&amp;arr.c);
    PrintPointerDetails(&amp;arr.a);
    PrintPointerDetails(&amp;arr.b);
    PrintPointerDetails(&amp;arr.c);
}

struct Foo
{
    public int a;
    public long b;
    public byte c;
}</pre></div>
<div class="jb51code"><pre class="brush:csharp;">| Expr            | Address         | Size | AlignedBySize | Addr/Size    |
| &amp;arr.a       | 654696769936    | 4    | True          | 163674192484 |
| &amp;arr.b       | 654696769940    | 8    | False         | 81837096242.5 |
| &amp;arr.c       | 654696769948    | 1    | True          | 654696769948 |
| &amp;arr.a       | 654696769949    | 4    | False         | 163674192487.25 |
| &amp;arr.b       | 654696769953    | 8    | False         | 81837096244.13 |
| &amp;arr.c       | 654696769961    | 1    | True          | 654696769961 |
</pre></div>
頁: [1]
查看完整版本: .NET 结构体字段的内存布局深度解析