0

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);
3
  • 1
    Can you share the signature of callback? Commented Sep 19, 2011 at 11:20
  • Added callback signature as requested. Commented Sep 19, 2011 at 11:29
  • What is the PInvoke equivalent; that you're using? Commented Sep 19, 2011 at 11:30

2 Answers 2

2

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.

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

Comments

0

Write managed callback according to your FillData prototype. Create unmanaged function pointer from it using Marshal.GetFunctionPointerForDelegate Method. Pass it to unmanaged code as callback function pointer.

1 Comment

I'm doing so. The question was, how to pass array from unmanaged code to managed, such that managed could fill it with data.

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.