【问题标题】:Reverse way to get double array values from IntPtr从 IntPtr 获取双数组值的反向方法
【发布时间】:2014-01-06 04:32:39
【问题描述】:

拥有一个双精度数组,我可以使用

将其转换为 IntPtr
public static IntPtr DoubleArrayToIntPtr(double[] d)
{
    IntPtr p = Marshal.AllocCoTaskMem(sizeof(double) * d.Length);
    Marshal.Copy(d, 0, p, d.Length);
    return p;
}

现在我只能以 IntPtr 方式从某个函数“GetPoint”获取数组值,如何从 IntPtr 检索双数组值?

例如,假设以下示例中的 path 是具有 (id, x,y,z) 结构的数据集,包含 5 个点坐标,如

(1, 10,10,0)
(2, 8 ,10,0)
(3, 9 ,50,0)
(4, 70,40,0)
(5, 60,60,0)

所以我想从该函数的 IntPtr "a" 中获取双数组值

我想这样:

for(int i = 0; i < path.GetNumberOfPoints(); i++)  //this does loop five times
{
    double[] pastPoints = new double[4]; //id,x,y,z
    IntPtr  a = DoubleArrayToIntPtr(pastPoints);
    path.GetPoint(i, a);
    System.Console.WriteLine(pastPoints[0]);
    System.Console.WriteLine(pastPoints[1]);
    System.Console.WriteLine(pastPoints[2]);
    System.Console.WriteLine(pastPoints[3]);
}

但只得到 0,我做错了什么?

【问题讨论】:

  • 只有当 path.GetPoint 实际将数据写入那些内存地址时,该代码才有效,我猜它不会。
  • 答案在问题中:Marshal.Copy

标签: c# arrays


【解决方案1】:

我没有使用 marshal 的经验,但我对 C++ 时代的指针有一些经验。

我希望你想这样做:

double[] pastPoints = new double[4]; //id,x,y,z
IntPtr a = Marshal.AllocCoTaskMem(sizeof(double) * pastPoints.Length);  // Allocate memory for result
path.GetPoint(i, a);    // Generate result.
Marshal.Copy(a, pastPoints, 0, pastPoints.Length);    // Copy result to array.
Marshal.FreeCoTaskMem(a);

System.Console.WriteLine(pastPoints[0]);
System.Console.WriteLine(pastPoints[1]);
System.Console.WriteLine(pastPoints[2]);
System.Console.WriteLine(pastPoints[3]);

【讨论】:

    猜你喜欢
    • 2011-10-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-02
    • 1970-01-01
    相关资源
    最近更新 更多