dotnet / dotnet-api-docs

.NET API reference documentation (.NET 5+, .NET Core, .NET Framework)
https://docs.microsoft.com/dotnet/api/
Other
732 stars 1.57k forks source link

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

Open AffluentOwl opened 5 months ago

AffluentOwl commented 5 months ago

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
dotnet-policy-service[bot] commented 5 months ago

Tagging subscribers to this area: @dotnet/area-system-runtime

tannergooding commented 5 months ago

Notably none of the examples given on the docs page are redundant. They are very explicitly showing the differences between under packing, overpacking, and matching the natural packing and contrasting it with how they impact fields whose natural packing are less than, equal to, or the same as the packing of the struct.

The example you gave explicitly shows another struct, but is in the same vein as the other examples the page already gives and is trying to showcase, which is that the actual packing of a struct is the lesser of the specified packing and natural packing of the struct. The natural packing of the struct is then the maximum of the actual packing of all fields of the struct.

AffluentOwl commented 5 months ago

This is why I always preferred PHP's documentation over MSDN. Their functionality to allow users to comment on the official documentation gives users an easy way to share additional knowledge and examples with each other. Combine this with the fact that github is often a walled garden to search engines, and we can only pray that this knowledge is distributed in the next release of ChatGPT.