Question

I am trying to import a C++ function in my C# code.

This function is defined as:

int SetPointers(int* ID, int* BufferID, int** Pointer, double** Time, int NumberOfPointers);

with ID an array of int, BufferId an array of int, Pointer an array of int, Time an array of double, and NumberOfPointers an int.

I have tried to use IntPtr without success.

Here is the latest code I tried:

[DllImport("open.dll", SetLastError = true, CharSet = CharSet.Auto, CallingConvention = CallingConvention.Cdecl)]
public unsafe static extern int SetPointers(int* ID, int* BufferID, ref IntPtr Pointer, ref IntPtr Time, int NumberOfPointers);
public unsafe int _SetPointers(int[] ID, int[] BufferID, ref int[] Pointer, ref double[] Time, int NumberOfPointers)
{
    IntPtr fQueue = IntPtr.Zero;
    IntPtr fTime = IntPtr.Zero;
    int breturn = -1;
    fixed (int* fId = ID)
    fixed (int* fBufferID = BufferID)
    fQueue = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(int)) * Pointer.Length);
    fTime = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(double)) * Timestamp.Length);
    breturn = SetPointers(fId, fBufferID, ref fQueue, ref fTime, NumberOfPointers);
    return breturn;
}

How can I do this?

Was it helpful?

Solution

First all, you might want to use IntPtr for your parameters rather than int[].

After this, I haven't tried it but to marshal pointers on pointers a "ref IntPtr" or "out IntPtr" would work.

public unsafe int _SetPointers(IntPtr ID, IntPtr BufferID, ref IntPtr Pointer, ref IntPtr Time, int NumberOfPointers);

Also have a look to this other question: How do I marshall a pointer to a pointer of an array of structures?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top