如果我用这个结构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)
这确实是错的.它是StructureToPtr()调用,无法复制足够的字节.你可以通过使用Debug + Windows + Memory + Memory1并在地址栏中输入"ptr"来看到这一点.使用sizeof运算符不正确,但实际上并不是问题的根源.无论数组长度如何,仅复制数组的第一个元素.不确定是什么导致了这个问题,我从来没有在pinvoke中使用固定.我只能推荐传统的pinvoke方式,它工作正常:
unsafe class Program {
[StructLayout(LayoutKind.Sequential)]
public struct Node {
public bool boolVar;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 2)]
public int[] y;
}
unsafe static void Main(string[] args) {
Node node = new Node();
node.y = new int[2];
node.y[0] = 1;
node.y[1] = 2;
node.boolVar = true;
int size = Marshal.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)
如果要将其提交给CLR互操作主机,请发布到connect.microsoft.com.
| 归档时间: |
|
| 查看次数: |
4689 次 |
| 最近记录: |