Tag: layoutkind.explicit

使用LayoutKind.Explicit的布尔编组,这是否已按设计破坏或失败?

首先,布尔类型被称为具有四字节值的默认编组类型。 以下代码有效: struct A { public bool bValue1; public int iValue2; } struct B { public int iValue1; public bool bValue2; } public static void Main() { int[] rawvalues = new int[] { 2, 4 }; A a = (A)Marshal.PtrToStructure(GCHandle.Alloc(rawvalues, GCHandleType.Pinned).AddrOfPinnedObject(), typeof(A)); Assert.IsTrue(a.bValue1 == true); Assert.IsTrue(a.iValue2 == 4); B b = (B)Marshal.PtrToStructure(GCHandle.Alloc(rawvalues, GCHandleType.Pinned).AddrOfPinnedObject(), typeof(B)); Assert.IsTrue(b.iValue1 […]

当子结构具有LayoutKind.Explicit时,不遵循LayoutKind.Sequential

运行此代码时: using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Runtime.InteropServices; namespace StructLayoutTest { class Program { unsafe static void Main() { Console.WriteLine(IntPtr.Size); Console.WriteLine(); Sequential s = new Sequential(); sA = 2; sB = 3; s.Bool = true; s.Long = 6; sCInt32a = 4; sCInt32b = 5; int* ptr = (int*)&s; Console.WriteLine(ptr[0]); Console.WriteLine(ptr[1]); Console.WriteLine(ptr[2]); Console.WriteLine(ptr[3]); […]