user3830999
user3830999

Reputation: 11

Using COM Object in C++ dll

I am writing a Win32 C++ DLL that uses the COM object(B.dll) which is made in C#. This dll(A.dll) provides CMyComObject class which creates a COM object and access to it. Here is my code.

void CMyComObject::CMyComObject() 
{    
  HRESULT result = CoInitialize(NULL);
  ...
  result = CoCreateInstance(CLSID_COMDLL, NULL, CLSCTX_INPROC_SERVER,     IID_COMDLL, reinterpret_cast<void**>(&MyComObject));
}

void CMyComObject::~CMyComObject() 
{
  ..
  CoUninitialize();
  ..
}

And then, here is a client program that loads A.dll and access to the COM object. This program creates several threads which load A.dll and create a COM object concurrently.

In this case, Is this correct to use CoInitialize() function or Should I use CoInitializeEx() function with COINIT_MULTITHREADED parameter? Or Is there any mistake I did? (I registered B.dll by commanding "reg_asm.exe B.dll B.tlb /codebase")

Sorry for my poor English.

Thanks.

Upvotes: 0

Views: 735

Answers (1)

Roman Ryltsov
Roman Ryltsov

Reputation: 69724

You are supposed to use CoInitialize[Ex]/CoUninitialize before and after any COM activity on that thread, and your choice between CoInitialize and CoInitializeEx with specific parameters depends on whether you prefer STA or MTA mode for your thread.

Having said that, your initialization:

  1. Does not depend on whether the COM object itself creates any threads
  2. Does not depend on other parts of your application possibly having other COM activity, including similar instantiation of the same COM class
  3. Entirely depends on your COM activity on the thread in question
  4. Does not normally happen in class constructor; it is typical to have COM initialization associated with top level thread code such as before windows message pump or at the very beginning of the thread procedure; putting it into constructor is an easy way to get into collision e.g. with another initialization (esp. using different apartment model) or too early uninitialization.

Summing it all once again, your initialization:

  • looks good if you are OK with COM single thread apartment model and you don't pass obtained pointer between threads
  • you would be better off moving CoInitialize and CoUninitialize calls out of constructor and associate it with thread code
  • be sure to check returned value to detect failures, esp. attempt to initialize mismatching apartment on the thread already having COM initialization
  • the part you missing is that you have to close all your COM activity before CoUninitialize call, including releasing your MyComObject pointer.

Upvotes: 1

Related Questions