Search code examples
c#.netarraysmanagedunmanaged-memory

Filling unmanaged array in managed code


I've got a managed program, which cooperates with unmanaged DLL library.

Library constructs an object, which asks (by callback function converted to delegate) managed host to fill unmanaged array. The array itself is passed via pointer (IntPtr) along with information about its size. The type is known to both sides. The point is, how can I safely fill the unmanaged array with data in managed code? Two restrictions apply: no unsafe code and preferably no additional arrays created. The array might be passed in another way if such exists.

Let the callback have the following prototype:

typedef void (__stdcall * FillData)(double * array, int count);

Let the delegate have the following prototype:

protected delegate void FillData(IntPtr array, int count);

Solution

  • If you want no unsafe code then you'll have to let the pinvoke marshaller copy the array. Declare the delegate type like this:

    private delegate MyUnmanagedCallback(
         [MarshalAs(UnmanagedType.LPArray, SizeParamIndex=1)] double[] array,
         int count);
    

    Be sure to store the delegate object so it can't be garbage collected.