Skip to content

Instantly share code, notes, and snippets.

@xoofx
Created November 11, 2020 19:37
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 xoofx/91c9a78b0327a33704bd5b983d193654 to your computer and use it in GitHub Desktop.
Save xoofx/91c9a78b0327a33704bd5b983d193654 to your computer and use it in GitHub Desktop.
StructLayoutBug
using System;
using System.Linq;
using System.Runtime.InteropServices;
// Requires the NuGet package https://www.nuget.org/packages/ObjectLayoutInspector/
namespace StructLayoutApp
{
[StructLayout(LayoutKind.Explicit)]
struct ExplicitLayoutStruct {
[FieldOffset(0)] public byte B00;
}
struct RegularStruct
{
public int Field;
}
struct BoolAndExplicitStruct
{
// bool AND a field with an explicit layout struct
// change the layout of this struct to Auto instead of sequential
public bool Bool;
//public char Char; // same behavior than bool
public ExplicitLayoutStruct ExplicitLayout;
public int Int32;
public RegularStruct RegularStruct;
public long Int64;
}
// Field Int64: starts at offset 0
// Field Int32: starts at offset 8
// Field Bool: starts at offset 12
// Field ExplicitLayout: starts at offset 16
// Field RegularStruct: starts at offset 24
class Program
{
static void Main(string[] args)
{
try
{
Console.WriteLine(
string.Join("\n",
ObjectLayoutInspector.TypeInspector.GetFieldOffsets<BoolAndExplicitStruct>()
.Select(tpl => $"Field {tpl.fieldInfo.Name}: starts at offset {tpl.offset}"))
);
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment