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 ",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.