Skip to content

Instantly share code, notes, and snippets.

@alexzzzz
Created September 15, 2020 19:18
Show Gist options
  • Save alexzzzz/3d8888df0ad8d28ee08e0f6bd0c65800 to your computer and use it in GitHub Desktop.
Save alexzzzz/3d8888df0ad8d28ee08e0f6bd0c65800 to your computer and use it in GitHub Desktop.
using System.Runtime.InteropServices;
class Program
{
[StructLayout(LayoutKind.Explicit)]
struct Union
{
[FieldOffset(0)]
public Foo foo;
[FieldOffset(0)]
public Bar bar;
}
class Foo { public Qux qux; }
class Bar { public int integer; }
class Qux { public int integer; }
static void Main()
{
var foo = default(Union);
foo.bar = new Bar { integer = 200_000 };
foo.foo.qux.integer = 0; // AccessViolationException: Attempted to read or write protected memory.
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment