1. 程式人生 > >COM元件的初始化

COM元件的初始化

    任何一個使用COM元件的windows程式在初始化COM庫的時候都要呼叫CoInitializeEx函式,每一個使用COM介面的執行緒必須單獨呼叫這個函式。下面是這個函式的宣告:
HRESULT CoInitializeEx(LPVOID pvReserved, DWORD dwCoInit);
第一個引數是保留引數,為空。第二個引數規定了將使用的執行緒模型。COM介面支援兩種不同的執行緒模型:單執行緒和多執行緒。一旦指定了單執行緒模型,就以意味著:
1.你將通過單執行緒來訪問每一個COM物件;在不同的執行緒之間不可以共享COM介面指標;
2.執行緒將會有一個訊息佇列。
如果上述任何一條不滿足的話,就需要指定multithreaded模型。下表為兩種模型的識別符號。 

Flag Description

COINIT_APARTMENTTHREADED Apartment threaded.
COINIT_MULTITHREADED Multithreaded.

你必須設定清楚上述標記位。通常來講,建立視窗的執行緒應該使用COINIT_APARTMENTTHREADED ,其它執行緒應該使用COINIT_MULTITHREADED。然而,一些COM元件需要特定的執行緒模型,在MSDN文件中會對這種情況有所介紹。
實際上,即使你指定了apartment執行緒,通過使用marshaling技術,執行緒之間共享介面也是有可能的;但是,你不能夠將一個介面指標複製給另外一個執行緒。下面給出了
HRESULT hr = CoInitializeEx(NULL, COINIT_APARTMENTTHREADED | COINIT_DISABLE_OLE1DDE);
這個函式返回型別HRESULT包含了正確或者錯誤的程式碼。下文中我將介紹錯誤處理。每一次成功呼叫CoInitializeEx之後,你必須呼叫CoUninitialize函式,該函式定義如下
CoUninitialize();

Note Actually, even if you specify apartment threading, it is still possible to share interfaces between threads, by using a technique called marshaling. Marshaling is beyond the scope of this module. The important point is that with apartment threading, you must never simply copy an interface pointer to another thread. For more information about the COM threading models, see Processes, Threads, and Apartments and Understanding and Using COM Threading Models.

In addition to the flags already mentioned, it is a good idea to set the COINIT_DISABLE_OLE1DDE flag in the dwCoInit parameter. Setting this flag avoids some overhead associated with Object Linking and Embedding (OLE) 1.0, an obsolete technology.