Export (0) Print
Expand All

Implementing Native COM Interfaces with Managed Extensions for C++

Visual Studio .NET 2003

The following sample shows how an object written in Managed Extensions for C++ implements native COM interfaces.

// com_comp.cpp
// compile with: /clr /LD
#define _ATL_ATTRIBUTES
#define _UNICODE
#define UNICODE

#include <atlbase.h>
#include <atlcom.h>
#include <vcclr.h>

using namespace System;

String* BSTR2SysString(BSTR bstr)
{
   int strLen = ::SysStringLen(bstr);
   Char ret[] = new Char [strLen];
   for(int idx = 0; idx < strLen; ++idx)
   {
      ret[idx] = bstr[idx];
   }
   return new String(ret);
};

// Implements the COM server's business logic.
class CTestBL
{
public:
   
   int TestMaxInt(int in1, int in2)
   {
      return (in1 > in2) ? in1 : in2;
   }
   
   BSTR TestString(BSTR in)
   {
      return ::SysAllocString(in);
   }
};

// implements COM architecture

[module(name="ClassicLib",type="dll" )];
[object, dual,
uuid("00000000-0000-0000-0000-000000000001")]
__interface ITestItf
{
   [id(0x01)]HRESULT TestMaxInt([in] int in1, [in] int in2, [out, retval] 
int *pRet);
   [id(0x02)]HRESULT TestString([in] BSTR in, [out, retval] BSTR* ret);
};  

[coclass,uuid("00000000-0000-0000-0000-000000000002")]
class CTestCOM: public ITestItf
{
public:
   
   HRESULT TestMaxInt(int in1, int in2, int *pRet)
   {
      *pRet = m_UnderObj.TestMaxInt(in1, in2);
      return S_OK;
   }
   
   HRESULT TestString(BSTR in, BSTR* ret)
   {
      *ret = m_UnderObj.TestString(in);
      return S_OK;
   }

private:
   CTestBL m_UnderObj;
};

public __gc class TestCOMPLUS
{
public:
   TestCOMPLUS() {m_pUnderObj = new CTestBL;}
   virtual ~TestCOMPLUS() {delete m_pUnderObj;}
   
   Int32 WrapTestMaxInt(Int32 in1, Int32 in2)
   {
      return m_pUnderObj->TestMaxInt(in1, in2);
   }
   
   String* WrapTestString(String* in)
   {
      const Char __pin* in1 = PtrToStringChars(in);
      BSTR bret = m_pUnderObj -> TestString(in1);
      String* ret = BSTR2SysString(bret);
      ::SysFreeString(bret);
      return ret;
   }

private:
   CTestBL* m_pUnderObj;

};

The client code is written using Managed Extensions for C++:

// mcpp_com_comp.cpp
// compile with: /clr
#using<mscorlib.dll>
using namespace System;
#using <com_comp.dll>

int main()
{
   TestCOMPLUS *c = new TestCOMPLUS;

   if (c -> WrapTestMaxInt(-10000, 9999909) != 9999909)
      return 1;

   if (c -> WrapTestString(S"testing through .NET wrapper") -> 
Equals(S"testing through .NET wrapper"))
      return 0;

   else
      return 2;
}

See Also

Interoperability in Managed Extensions for C++
Show:
© 2014 Microsoft