IntPtr 地址增量(不是值)

本文关键字:地址 IntPtr | 更新日期: 2023-09-27 18:32:54

我有一个C++DLL,它具有从设备发送数据的函数。从我的托管 C# 代码中,我调用C++函数 positionCallback。这里请注意根据定义的位置 pos 是三个指针的数组,指向位置数组。

public void positionCallback(uint devNo,uint count,uint index,ref System.IntPtr pos,ref System.IntPtr mrk)

现在我的问题是我想提取这 3 个数组中每个数组的数据,但我只能获取数组 1 的数据,而对于其余 2,我得到了垃圾值。下面是我正在尝试的代码

 // Copy the unmanaged array to managed memory for Axis 2
IntPtr ptr2 = IntPtr.Add(pos,2*sizeof(Int64));
 Marshal.Copy(pos,managedArrayAxis1,0,(int)count);
 // Copy the unmanaged array to managed memory for Axis 2
 Marshal.Copy(ptr2, managedArrayAxis2, 0, (int)count);

上面的代码只为托管数组轴 1 提供正确的数据,但对于托管阵列轴 2,垃圾数据正在收集。我是否错误地将 IntPtr 地址递增为 pos?

请帮忙!

IntPtr 地址增量(不是值)

pos参数实际上是指向双精度数组的指针数组的指针,因此您需要取消引用它两次。您的代码发生的情况是,ref会自动取消对指针数组的指针的引用,但您得到的pos只是 3 个二级指针中的第一个指针,无法到达其他两个指针。

要获取原始指针,您需要删除pos参数上的 ref 关键字。然后将 pos 指向的数据复制到一个 IntPtr s 的数组中,您将不需要任何指针算法:

public void positionCallback(uint devNo,uint count,uint index,System.IntPtr pos,ref System.IntPtr mrk)
// copy the array of pointers
IntPtr[] arrays = new IntPtr[3];
Marshal.Copy(pos, arrays, 0, 3);
// Copy the unmanaged array to managed memory for Axis 2
Marshal.Copy(arrays[0],managedArrayAxis1,0,(int)count);
// Copy the unmanaged array to managed memory for Axis 2
Marshal.Copy(arrays[1], managedArrayAxis2, 0, (int)count);