Groups | Blog | Home
all groups > dotnet interop > march 2007 >

dotnet interop : How to marshal a variable length array in a callback function from unmanaged to managed code?



gernot
3/23/2007 4:24:25 PM
Hi,

I want to marshal the following C++ struct to a managed callback
function:

struct CALLBACK_DATA
{
LPBYTE pArray; // byte array
UINT uArrayLen; // byte count
};

The C++ function expects the following callback type:

typedef BOOL (CALLBACK *CALLBACK_FUNC)(const CALLBACK_DATA *pData,
LPVOID pvParam);

In C# first I import the C++ function:

[DllImport("unmanaged.dll", EntryPoint = "Func")]
static extern bool Func(CallbackFunc callback, IntPtr param);

Where CallbackFunc is declared as a delegate:

public delegate bool CallbackFunc(CallbackData data, IntPtr param);

Then I define the callback and do the call:

// the callback function
public static bool Callback(CallbackData data, IntPtr param)
{
}

CallbackFunc callback = new CallbackFunc(Callback);
Func(callback, param);

The question is how do I have to declare CallbackData?

[StructLayout(LayoutKind.Sequential)]
public class CallbackData
{
[MarshalAs(UnmanagedType.ByValArray, SizeConst=100)] // error!
byte[] array;
uint arrayLen;
}

I cannot find attibutes that fit for this situation.
Anyway the array is not const size!

Can anybody help?

Thanks,
Gernot
mehr13 NO[at]SPAM hotmail.com
3/25/2007 6:17:07 AM
[quoted text, click to view]

Declare the array parameter as IntPtr,
[StructLayout(LayoutKind.Sequential)]
public class CallbackData
{
IntPtr array;
uint arrayLen;
}

Then use Marshal class to handle the array.

Hope this helps
MH
gernot
3/25/2007 8:44:06 AM
[quoted text, click to view]

It did help, thank you.
AddThis Social Bookmark Button