I am confused by this documentation:
A thread must call CoUninitialize once for each successful call it has made to the CoInitialize or CoInitializeEx function, including any call that returns S_FALSE. Only the CoUninitialize call corresponding to the CoInitialize or CoInitializeEx call that initialized the library can close it.
It sounds like it is saying a successful call to CoInitialize/Ex()
includes those that return S_FALSE
?
Or, CoUninitialize()
must be called only if CoInitialize/Ex()
returns S_OK
?
Or, should it be called regardless of the return value?
CodePudding user response:
Per the documentation:
A thread must call
CoUninitialize
once for each successful call it has made to theCoInitialize
orCoInitializeEx
function, including any call that returnsS_FALSE
. Only theCoUninitialize
call corresponding to theCoInitialize
orCoInitializeEx
call that initialized the library can close it.
Typically, the COM library is initialized on a thread only once. Subsequent calls to CoInitialize or CoInitializeEx on the same thread will succeed, as long as they do not attempt to change the concurrency model, but will return S_FALSE. To close the COM library gracefully, each successful call to CoInitialize or CoInitializeEx, including those that return S_FALSE, must be balanced by a corresponding call to CoUninitialize. However, the first thread in the application that calls CoInitialize with 0 (or CoInitializeEx with COINIT_APARTMENTTHREADED) must be the last thread to call CoUninitialize. Otherwise, subsequent calls to CoInitialize on the STA will fail and the application will not work.
CoInitializeEx must be called at least once, and is usually called only once, for each thread that uses the COM library. Multiple calls to CoInitializeEx by the same thread are allowed as long as they pass the same concurrency flag, but subsequent valid calls return S_FALSE. To close the COM library gracefully on a thread, each successful call to CoInitialize or CoInitializeEx, including any call that returns S_FALSE, must be balanced by a corresponding call to CoUninitialize.
All of the constants with the prefix "E_" are error codes. The constants
S_OK
andS_FALSE
are both success codes. Probably 99% of COM methods returnS_OK
when they succeed; but do not let this fact mislead you. A method might return other success codes, so always test for errors by using theSUCCEEDED
orFAILED
macro......
The success code
S_FALSE
deserves mention. Some methods useS_FALSE
to mean, roughly, a negative condition that is not a failure. It can also indicate a "no-op"—the method succeeded, but had no effect. For example, the CoInitializeEx function returns S_FALSE if you call it a second time from the same thread. If you need to differentiate betweenS_OK
andS_FALSE
in your code, you should test the value directly, but still useFAILED
orSUCCEEDED
to handle the remaining cases...