1

I have a c++ class which needs to interact with a .NET dll using COM interop.

I have:

1. A method called from the C++ which operating object is the .net instance:

   m_pCommManager.CreateInstance(__uuidof(CHmHTTPManager));
    m_pCommManager->Communicate(/*string parameter*/);

2. A .net interface with the following method, which the C++ class should comply to:

 void ResponseRecieved(/*string parameter*/)

My question is: What is the parameter type I should select that is:

A. Easy for manipulation as a string on both sides (even through casting).

B. Acceptable by both environments (I cannot use "string" for C++ and .net as it's not the same)

Concrete usage examples are more than welcome.

user181218
  • 1,655
  • 5
  • 28
  • 42

1 Answers1

0

You should use a BSTR string in C++.

From MSDN:

A BSTR is a composite data type that consists of a length prefix, a data string, and a terminator. The following table describes these components.

BSTRs are allocated using COM memory allocation functions, so they can be returned from methods without concern for memory allocation.

In the IDL file for your COM object it would be:

HRESULT mySampleMethod([in] BSTR mySampleParam);

How the actual code in C++ will look like will depend on the type of COM object/Type Library you are developing (I mean whether you are using an MFC-based COM object or an ATL-based one). On any case I recommend you to use the wizard from Visual Studio to create/modify your type library.

In the .Net side, you just use the normal string type, and it will be marshaled automatically if the parameter is defined as BSTR in the type library of your COM object.

You may also find this question useful:

Convention for passing BSTRs into COM functions from C# (COM interop)

Community
  • 1
  • 1
yms
  • 10,361
  • 3
  • 38
  • 68