2

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?

8
  • What does malloc have to do with the question? Commented Nov 26, 2013 at 15:51
  • You need to show, how this function is used in unmanaged code. Or show the function code. Commented Nov 26, 2013 at 15:54
  • Sorry, I meant marshal Commented Nov 26, 2013 at 15:54
  • I can't modify that code, and it is very complex. Basically, ID, BufferId and NumberOfPointers are only read by the function and Pointer and Time are like returned values. Does this help? Commented Nov 26, 2013 at 15:55
  • I dont think you are doing the right thing. Double referencing is probably an out parameter - Please read this stackoverflow.com/questions/6810419/… Commented Nov 26, 2013 at 16:05

1 Answer 1

2

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?

Sign up to request clarification or add additional context in comments.

1 Comment

First two parameters are fine as arrays

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.