Skip to content

StructLayoutAttribute.Pack Field should give an example of nested packing #9985

Open
@AffluentOwl

Description

@AffluentOwl

Consider the following non-obvious behavior where an inner struct's packing can affect where it is laid out in a parent struct. The documentation gives 7 nearly redundant examples, but does not give an example of nested packing.

[StructLayout(LayoutKind.Sequential, Pack = 4)]
public struct MINIDUMP_INCLUDE_MODULE_CALLBACK1
{
  public ulong BaseOfImage;
}

public struct MINIDUMP_INCLUDE_MODULE_CALLBACK2
{
  public ulong BaseOfImage;
}

public struct Test1
{
  public byte x;
  public MINIDUMP_INCLUDE_MODULE_CALLBACK1 y;
}

public struct Test2
{
  public byte x;
  public MINIDUMP_INCLUDE_MODULE_CALLBACK2 y;
}

{
  Test1 a = new();
  byte* addr = (byte*)&a;
  Console.WriteLine($"{(byte*)&a.x - addr} {(byte*)&a.y - addr} {sizeof(Test1)}");
}

{
  Test2 a = new();
  byte* addr = (byte*)&a;
  Console.WriteLine($"{(byte*)&a.x - addr} {(byte*)&a.y - addr} {sizeof(Test2)}");
}
0 4 12
0 8 16

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions