【问题标题】:IntPtr Address increment (not value)IntPtr 地址增量(不是值)
【发布时间】:2014-12-02 19:13:08
【问题描述】:

我有一个 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);

上面的代码只为 managedArrayAxis1 提供了正确的数据,但对于 managedArrayAxis2,垃圾数据正在收集。我是否错误地增加了 pos 的 IntPtr 地址?

请帮忙!

【问题讨论】:

  • 你确定 Int64 是正确的吗?如果它应该是 int 并且您使用的是 Int64,那会导致问题。
  • Int32 也为 managedArrayAxis2 提供垃圾值。所以尝试了这两种东西。任何其他建议都会有所帮助!
  • 您通过引用传递这些指针这一事实如何?我想这看起来像 c++ 库的 int** 。你确定这就是 c++ 方法要找的吗?
  • 在 C++ 中它看起来像 static void positionCallback( unsigned int devNo, unsigned int count, unsigned int index, const double * const pos[3], const bln32 * const mrk[3] ),我是获取一组数组的数据,但对于另一组我得到垃圾。在指向正确的数组地址时看起来像“pos”,但 ptr2 无法指向正确的位置@pquest
  • 为什么不使用 sizeof double?

标签: c# .net marshalling intptr


【解决方案1】:

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

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

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);

【讨论】:

  • @Ben,为什么“不”?你说得对,只有两层——最上面一层是double * 的数组,我将它复制到arrays 中,第一个是Marshal.Copy。这允许我访问我刚刚从问题中复制的其他两个 Marshal.Copy() 调用所做的 3 第二层数组。你有什么问题?
  • 对不起,我把你的第一句话误解为三重指针。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-08-19
  • 1970-01-01
  • 2022-12-22
  • 2020-04-07
  • 1970-01-01
相关资源
最近更新 更多