Search code examples
c#c++.netcommarshalling

How to Return and consume custom struct object from C++ COM component into C# application


I have created a simple COM component in C++ and added a method like this

interface IMathControl : IDispatch{

    HRESULT AddTwoNumbers(

                [in]  DWORD Number1,

                [in]  DWORD Number2,

                [out] DWORD *pResult

            );
};

I have consumed above component in my C# application and it works fine.

Now, I have a struct defined in C++ as this

struct AttributeValueInfo
{
    string attribute;
    string value;
    string description;
};

My questions are:

How I can define a method which should return the result of AttributeValueInfo type in my C++ COM component ?

How I will consume that resultant struct AttributeValueInfo in my C# application ?

I think i need to do marshaling but don't know where to start. Can someone point the steps or a simple code snippet for above scenario.

Any help will be appreciated.


Solution

  • That is not possible. Only a C++ compiler can ever generate code to properly read the value of an std::string. With the additional restriction that it is the exact same version of the compiler with the exact same settings and using the exact same memory allocator. Interop capabilities for standard C++ classes compare unfavorably to those of a stone brick. C++ doesn't have anything similar to the kind of VM guarantees you get in C#, ensuring that basic rules like object layout and allocation is guaranteed for any code that runs in the process.

    You must use a string type that has interop guarantees. That's BSTR in COM, directly supported and assumed by the CLR.

    Using structs is pretty troublesome as well, their layout are heavily dependent on compiler settings. A declaration of the struct must appear in the type library you author, the CLR will use the IRecordInfo interface to safely access the struct members. Otherwise the kind of restriction that disappears when you realize that a struct is equivalent to a class with nothing but properties.