Search code examples
c#c++structcom-interopidl

define a structure in C++ IDL, then MarshalAs() appropriately in C#


I have a C++ COM server that fills a C# caller's structure with data.

The structure is defined in the C++ IDL, something like the following:

interface Icontrol : IDispatch{
    [ 
    uuid(...), 
    version(1.0) ]
    typedef struct testStructure
    { 
        int x;
        int y;
        int z;
        ...
    } testStructure; 

    ...
    [id(9)] HRESULT getStruct([ref,in,out] testStructure * theData);
    ...

Then, in the C# code:

EO_Lib.testStructure test = new EO_Lib.testStructure();
EO_Lib.getStruct(ref test);

I can make this work no problem with a regular .DLL by simply using MarshallAs in a C# structure for the fields non-native to C#. But I can't get that to work on a COM .DLL. I suspect it's because of my lack of knowledge about IDL.

What I need to be able to do is call getStruct() with a new C# type that I've created with appropriate MarshallAs() information. How do I do this?

I am using Visual Studio 2010 MFC/ATL C++ and C# .NET 4 Framework, if it helps.


Solution

  • While not an actual solution to the question, the following obviates the reason for my question.

    From: http://msdn.microsoft.com/en-us/library/75dwhxf7(v=vs.100).aspx

    Structures that are returned from platform invoke calls must be blittable types. Platform invoke does not support non-blittable structures as return types.

    So basically, you can't do what I wanted to do.

    If you ignore the COM aspect, BrokenGlass's solution here answers the convert-one-structure-to-another question.