Created
November 28, 2020 23:22
-
-
Save GrabYourPitchforks/32a640a340345a0f31e0d67ce3038fd8 to your computer and use it in GitHub Desktop.
FieldOffset as unsafe
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Need to figure out how to work this in to the document being created at dotnet/runtime#41418.