Skip to content

Instantly share code, notes, and snippets.

@PJB3005
Created November 12, 2022 10:23
Show Gist options
  • Save PJB3005/7dd468f3026c6f5121e085326ef23590 to your computer and use it in GitHub Desktop.
Save PJB3005/7dd468f3026c6f5121e085326ef23590 to your computer and use it in GitHub Desktop.
// For various practical reasons,
// you *can only* have the union type contain fields of the struct itself.
// i.e. you can't deconstruct the field structs into their component fields.
// Consider a union of these two types:
[StructLayout(LayoutKind.Explicit)]
public struct A
{
// NOTE: while structs in C# default to being emitted as LayoutKind.Sequential,
// CoreCLR actually *ignores* sequential layout if the type has managed references inside it.
// I believe this is not the case for explicit struct layout however.
[FieldOffset(0)]
public int X;
[FieldOffset(4)]
public object Y;
}
[StructLayout(LayoutKind.Explicit)]
public struct B
{
[FieldOffset(0)]
private nint X;
}
// What layout would you use to make a union of these?
// You could emit the following into your assembly...
[StructLayout(LayoutKind.Explicit)]
public struct Union
{
[FieldOffset(0)]
public A _A;
[FieldOffset(0)]
public B _B;
}
// But that's only valid on a 32-bit runtime. On 64-bit the types overlap and it fails to load.
// God forbid that B is in another assembly and somebody changes the layout of B to this:
[StructLayout(LayoutKind.Explicit)]
public struct B
{
[FieldOffset(0)]
private int X;
[FieldOffset(0)]
private int Y;
}
// Now there's **no** way to make it work ahead of time.
// Really, struct DUs would be way too flaky and not work in 99% of cases.
// The C# compiler would be forced to emit a sequential type with no overlap for almost all cases.
// Because of factors like this and all other general fragility concerns,
// I don't think anybody at Microsoft wants to seriously do this in an ecosystem
// that's intended for strong dynamic loading.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment