dotnet / dotnet/dotnet-api-docs
StructLayoutAttribute.Pack Field should give an example of nested packing
- Dominant language
- C#
- Stars
- 949
- Forks
- 1.7k
- Avg merge
- 3d 27m
- Merged PRs (30d)
- 49
Description
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.
```c#
[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)}");
}
```
```txt
0 4 12
0 8 16
```
Contributor guide
Assessment
This issue has not been assessed yet.