Marshall double[] to IntPtr in C#?

本文关键字:in IntPtr to double Marshall | 更新日期: 2023-09-27 18:32:24

我正在尝试在 C# 中将 double[] 转换为 IntPtr。这是我要转换的数据:

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

这是我将在 Intptr 中输入的函数,它是从上面的数组转换而来的:

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

我应该如何完成这项工作?

Marshall double[] to IntPtr in C#?

您可以尝试使用 Marshal.AllocCoTaskMemMarshal.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);
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();
}

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

您希望如何将双精度转换为整数? 您应该预料到数据截断。

你可以做这样的事情:

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