Does anyone know how to properly marshal the data from legacy app to
a .Net component? The legacy app uses the following IDL interface
definition:

interface IMyInterface2 : IUnknown
{
HRESULT doit( [in, size_is(msgLength)]UCHAR* msg, [in] ULONG
msgLength );
};

When my legacy COM Client calls my .Net component that implements this
interface, an access violation (0xC0000005) exception is thrown. I've
tried everything and can not figure out why the exception is thrown in
the
COM Client.

Here is the COM Client:

#include "stdafx.h"
#include "IMyInterface2_h.h"
#include "IMyInterface2_i.c"

int _tmain(int argc, _TCHAR* argv[])
{
HRESULT hr = S_OK;
hr = ::CoInitialize( NULL );
CLSID rcid = { 0x5F850215, 0x7AC2, 0x48b8, { 0xA8, 0xCF, 0xA0, 0x08,
0xF7, 0x33, 0xD6, 0x61 } };

{
CComPtr<IMyInterface2> iMyInterface2;
hr = iMyInterface2.CoCreateInstance( rcid, NULL, CLSCTX_INPROC_SERVER
);
UCHAR* pBytes = (UCHAR*)::CoTaskMemAlloc( 20 );
::ZeroMemory( pBytes, 20 );
iMyInterface2->doit( pBytes, 20 );
}
::CoUninitialize();

return 0;
}

The exception is thrown on the statement:
iMyInterface2->doit( pBytes, 20 );
The call never gets to the .Net component's method

And here is the .Net service component. The .Net component must be
copied in the same directory as the COM client.

using System;
using System.Runtime.InteropServices;

namespace ComSrv
{
[GuidAttribute("5F850215-7AC2-48b8-A8CF-A008F733D661")]
public class MyClass : IMyInterface2
{
public void doit( byte[] msg, ulong msgLength )
{
}
}

[ComImport]
[GuidAttribute("B55AFAEB-BC7D-4ca9-8065-F9A45FE378B6")]
[InterfaceTypeAttribute
ComInterfaceType.InterfaceIsIUnknown)]
public interface IMyInterface2
{
void doit(
[In, MarshalAs( UnmanagedType.LPArray,
SizeParamIndex=1, ArraySubType=UnmanagedType.U1 )]byte[]
msg, [In]ulong msgLength );
}
}