Search code examples
c#arraysmarshallingintptr

Marshall double[] to IntPtr in C#?


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?


Solution

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