# CoInitializeEx

Initializes the Component Object Model (COM) for use by the current thread. You can call CoinitializeEx in preference to calling CoInitialize, the implementation of which simply calls CoInitializeEx, specifying COINIT_APARTMENTTHREADED.

HRESULT CoInitializeEx(

void * pvReserved, | //Reserved
DWORD dwCoInit | //COINIT value
); |

Parameters

pvReserved
  [in] Reserved for future use; must be NULL.
dwCoInit
  [in] This may contain any set of values from the COINIT enumeration except for both apartment and multi-threaded.

Return Values

This function supports the standard return value E_INVALIDARG, as well as the following:

S_OK
  Indicates success.
RPC_E_CHANGED_MODE
  A previous call to CoInitializeEx specified a concurrency model for this thread different from the one currently specified for this thread.

Remarks

CoInitializeEx initializes the Component Object Model (COM) for use by the current thread. The dwCoInit parameter specifies the type of concurrency control multi-threaded or apartment-threaded required by objects created by this thread. A call to CoInitializeEx specifying COINIT_APARTMENTTHREADED is equivalent to a call to CoInitialize, because prior to NT 4.0, the default concurrency control required by objects was apartment-threaded.

Objects created on a multi-threaded COM thread must be able to receive calls on their methods from other threads at any time. Typically, you would implement some form of concurrency control in a multi-threaded object’s code using Win32 synchronization primitives, such as critical sections, semaphores, or mutexes, to protect the object’s data. Objects created on an apartment-threaded COM thread receive calls on their methods from their apartment’s thread only, so calls are serialized, and calls only arrive at message-queue boundaries (PeekMessage, SendMessage).

Applications must call CoInitializeEx or CoInitialize before making any other COM library calls except the CoGetMalloc function and other memory allocation calls (CoTaskMemAlloc, CoTaskMemFree, CoTaskMemReAlloc, and the IMalloc methods on the task allocator supplied by CoGetMalloc).

Typically, CoInitializeEx is called only once by each thread in the process that uses the OLE library. Multiple calls by the same thread are allowed so long as they pass the same concurrency flag, but subsequent valid calls return S_FALSE. To close the library gracefully, each successful call to CoInitialize or CoInitializeEx, including those that return E_INVALIDARG, must be balanced by a corresponding call to CoUninitialize.

Internally, the OleInitialize function calls CoInitializeEx with the COINIT_APARTMENTTHREADED flag. This implies that a thread that uses CoInitializeEx to initialize a thread for multi-threaded object concurrency may not use the features enabled by OleInitialize, because OleInitialize will fail.

See Also

COINIT, CoInitialize, Processes and Threads