Skip to content

Instantly share code, notes, and snippets.

@GrabYourPitchforks
Created November 28, 2020 23:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save GrabYourPitchforks/32a640a340345a0f31e0d67ce3038fd8 to your computer and use it in GitHub Desktop.
Save GrabYourPitchforks/32a640a340345a0f31e0d67ce3038fd8 to your computer and use it in GitHub Desktop.
FieldOffset as unsafe
using System;
using System.Runtime.InteropServices;
namespace FieldOffsetSample
{
class Program
{
static void Main(string[] args)
{
MyStruct myStruct = default;
myStruct.Byte0 = 1;
myStruct.Byte4 = 2;
DoIt(myStruct.Bool0, myStruct.Bool4);
}
static void DoIt(bool a, bool b)
{
Console.WriteLine($"a is {a}"); // prints 'True'
Console.WriteLine($"b is {b}"); // prints 'True'
Console.WriteLine($"a && b is {a && b}"); // prints 'False'
}
}
[StructLayout(LayoutKind.Explicit)]
struct MyStruct
{
[FieldOffset(0)]
public byte Byte0;
[FieldOffset(0)]
public bool Bool0;
[FieldOffset(4)]
public byte Byte4;
[FieldOffset(4)]
public bool Bool4;
}
}
@GrabYourPitchforks
Copy link
Author

Need to figure out how to work this in to the document being created at dotnet/runtime#41418.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment