Com組件開發過程中用的不多,資料也不多,故記錄開發Com組件中的部分問題。
在這一篇文章里,講解了如何使用VS2010創建Com組件。現在基於該文章創建的Com組件接口,創建VC++項目來調用該接口。
使用流程
新建win32控制台項目。
主文件代碼如下:
#include "stdafx.h" #include "../testCom/testCom_i.h" #include "../testCom/testCom_i.c" int _tmain(int argc, _TCHAR* argv[]) { HRESULT hr; IMyClass *pCom = NULL; CoInitialize(NULL); hr = CoCreateInstance(CLSID_MyClass,NULL,1,IID_IMyClass,(LPVOID*)&pCom); if (SUCCEEDED(hr)) { LONG res; pCom->Add(2,3,&res); printf("2+3=%d\n",res); } CoUninitialize(); return 0; }
代碼說明:
#include "../testCom/testCom_i.h"
#include "../testCom/testCom_i.c"
是將com組件定義接口的文件包含到本工程中,這樣操作后才可以在后面直接調用Com接口函數。
調用Com組件前必須調用CoInitialize(NULL);
調用完成后需要釋放CoUninitialize();
CoCreateInstance用於創建一個Com實例,函數說明如下:
HRESULT CoCreateInstance( __in REFCLSID rclsid, __in LPUNKNOWN pUnkOuter, __in DWORD dwClsContext, __in REFIID riid, __out LPVOID *ppv ); rclsid [in] The CLSID associated with the data and code that will be used to create the object. pUnkOuter [in] If NULL, indicates that the object is not being created as part of an aggregate. If non-NULL, pointer to the aggregate object's IUnknown interface (the controlling IUnknown). dwClsContext [in] Context in which the code that manages the newly created object will run. The values are taken from the enumeration CLSCTX. riid [in] A reference to the identifier of the interface to be used to communicate with the object. ppv [out] Address of pointer variable that receives the interface pointer requested in riid. Upon successful return, * ppv contains the requested interface pointer. Upon failure, * ppv contains NULL.
