I am porting an application from 32-bit to 64-bit (x64 platform) and I have a problem with interop between a native in-proc COM server and a C# application. Everything works nicely when the COM server is used from a C++ app (regardless of 32- or 64-bit), but only works in 32-bit when called from a C# app. The 64-bit version of the COM server DLL and the C# app do not work well together.

I traced the problem to the marshaling of a custom defined structure. It looks like this (actually I have several, and all behave the same):

Code:
 
[uuid(6F13C84D-0E01-48cd-BFD4-F7071A32B49F)] struct S
{
      long a;
      BSTR b;
      long c;
      BSTR d;
      long e;
      BSTR f;
      BSTR g;
      BSTR h;
      BSTR i;
      long j;
      BSTR k;
      long l;
      BSTR m;
      long n;
};
There is a COM method that returns an array of such structures. Its signature is

Code:
[id(54)] HRESULT GetListOfStructs(SAFEARRAY(struct S)* arrRes);
When the call from the COM method returns to the managed app that consumes the COM object, an access violation occurs (in 64-bit). If the BSTR members are left uninitialized, there is no access violation.

I read that custom structures are problematic, but 64-bit version of midl.exe should be able to handle them. I compiled the .IDL file for x64 with both 32-bit and 64-bit version of midl.exe from Windows SDK v7.0A, and there is no difference. Here is how the proxy/stub file header is when compiled for:

32-bit (win32) with 32-bit midl.exe
Code:
 /* File created by MIDL compiler version 7.00.0500 */
/* at Thu Sep 22 17:52:25 2011
 */
/* Compiler settings for .\RAC.idl:
    Oicf, W1, Zp8, env=Win32 (32b run)
    protocol : dce , ms_ext, c_ext, robust
    error checks: allocation ref bounds_check enum stub_data 
    VC __declspec() decoration level: 
         __declspec(uuid()), __declspec(selectany), __declspec(novtable)
         DECLSPEC_UUID(), MIDL_INTERFACE()
*/
//@@MIDL_FILE_HEADING(  )

#if !defined(_M_IA64) && !defined(_M_AMD64)
64-bit (x64) with both 32-bit and 64-bit midl.exe
Code:
/* File created by MIDL compiler version 7.00.0500 */
/* at Thu Sep 22 17:58:46 2011
 */
/* Compiler settings for .\RAC.idl:
    Oicf, W1, Zp8, env=Win64 (32b run)
    protocol : dce , ms_ext, c_ext, robust
    error checks: allocation ref bounds_check enum stub_data 
    VC __declspec() decoration level: 
         __declspec(uuid()), __declspec(selectany), __declspec(novtable)
         DECLSPEC_UUID(), MIDL_INTERFACE()
*/
//@@MIDL_FILE_HEADING(  )    

#if defined(_M_AMD64)
Any help is greatly appreciated.