1

I am trying to convert double[] to IntPtr in C#. Here is the data I am going to convert:

double[] rotX = { 1.0, 0.0, 0.0 };
double[] rotY = { 0.0, 1.0, 0.0 };
double[] rotZ = { 0.0, 0.0, 1.0 };

Here is the function I am going to feed in the IntPtr, which is converted from the array above:

SetRotationDirection(IntPtr rotX, IntPtr rotY, IntPtr rotZ);

How should I do the job?

4

4 回答 4

3

您可以尝试使用Marshal.AllocCoTaskMemand Marshal.Copy

double[] d = new double[] {1,2,3,4,5 };
IntPtr p = Marshal.AllocCoTaskMem(sizeof(double)*d.Length);
Marshal.Copy(d, 0, p, d.Length);
于 2013-09-23T19:19:29.910 回答
1
using System.Runtime.InteropServices;

/* ... */

double[] rotX = { 1.0, 0.0, 0.0 };
double[] rotY = { 0.0, 1.0, 0.0 };
double[] rotZ = { 0.0, 0.0, 1.0 };

var gchX = default(GCHandle);
var gchY = default(GCHandle);
var gchZ = default(GCHandle);

try
{
    gchX = GCHandle.Alloc(rotX, GCHandleType.Pinned);
    gchY = GCHandle.Alloc(rotY, GCHandleType.Pinned);
    gchZ = GCHandle.Alloc(rotZ, GCHandleType.Pinned);

    SetRotationDirection(
        gchX.AddrOfPinnedObject(),
        gchY.AddrOfPinnedObject(),
        gchZ.AddrOfPinnedObject());
}
finally
{
    if(gchX.IsAllocated) gchX.Free();
    if(gchY.IsAllocated) gchY.Free();
    if(gchZ.IsAllocated) gchZ.Free();
}
于 2013-09-23T19:16:30.270 回答
0

IntPtr 表示平台特定的整数。它的大小是 4 或 8 字节,具体取决于目标平台位数。

您想如何将双精度数转换为整数?您应该期望数据截断。

于 2013-09-23T19:17:13.270 回答
0

你可以这样做:

for(int i = 0; i < 3; i++) {
  var a = new IntPtr(Convert.ToInt32(rotX[i]));
  var b = new IntPtr(Convert.ToInt32(rotY[i]));
  var c = new IntPtr(Convert.ToInt32(rotZ[i]));
  SetRotationDirection(a, b, c);
}
于 2013-09-23T19:18:34.813 回答