CoInitialize() / CoUninitialize() calls pairing

2019-01-29 07:20发布

问题:

I have a single-threaded application that uses COM objects. At the beginning I in effect call CoInitialize(0) twice - once in my code and the second time in the code of another subsystem of the application. The first call returns S_OK, the second returns S_FALSE - exactly as MSDN says.

When the application stops it calls CoUninitialize() twice but between those calls it tries to call methods of some COM objects - those calls just crash with access violation because I suppose the COM objects are finalized and released at the first call to CoUnitialize(). If I remove the duplicating calls to CoInitialize()/CoUnitialize() it works allright.

But why is this? MSDN says I can call CoInitialize() repeatedly and must only pair those calls with the matching number of CoUnitialize() calls.

Why are COM objects finalized at the first call to CoUninitialize().

回答1:

sounds like you're doing it correct, however, check to be sure your couninitialize calls are done after the main window for the app has closed and after the message loop for that window has run finished.