如果我用这个结构StructureToPtr编组,然后再用它解组PtrToStructure,我的第一个节点有y = {1,2},而我的第二个节点有y = {1,0}.
我不知道为什么,也许我的结构在某种程度上是坏的?bool从结构中删除它使它工作.
using System;
using System.Runtime.InteropServices;
namespace csharp_test
{
unsafe class Program
{
[StructLayout(LayoutKind.Sequential)]
public struct Node
{
public bool boolVar;
public fixed int y[2];
}
unsafe static void Main(string[] args)
{
Node node = new Node();
node.y[0] = 1;
node.y[1] = 2;
node.boolVar = true;
int size = sizeof(Node);
IntPtr ptr = Marshal.AllocHGlobal(size);
Marshal.StructureToPtr(node, ptr, false);
Node node2 = (Node)Marshal.PtrToStructure(ptr, typeof(Node));
Marshal.FreeHGlobal(ptr);
}
}
}
Run Code Online (Sandbox Code Playgroud)