rn CWinApp::ExitInstance();
}
第二节 客户
程序 使用COM组件服务器的客户
程序关键步骤是:初始化COM库,创建组件对象并获取IUnknown接口指针,
查询接口并使用,释放组件.
#include "ITimeLogServer.h"
//初始化COM库,对组件实例化
HRESULT hResult;
IUnknown* pIUnknown;
hResult = ::CoInitialize(NULL);
if(FAILED(hResult))
{
::AfxMessageBox("不能初始化COM库!");
return FALSE;
}
//创建组件实例
pIUnknown = NULL;
hResult = ::CoCreateInstance(CLSID_TimeLogServer,NULL,
CLSCTX_INPROC_SERVER,IID_IUnknown,(void**)&pIUnknown);
if(FAILED(hResult))
{
pIUnknown = NULL;
::AfxMessageBox("不能创建TimeLog对象!");
return FALSE;
}
//
查询接口并使用
if(pIUnknown!=NULL)
{
ITimeLog* pITimeLog;
HResult=pIUnknown->QueryInterface(IID_ITimeLog,(void**)&pITimeLog);
if(FAILED(hResult))
{
::AfxMessageBox("不能获取接口ITimeLog!");
pIUnknown->Release();
return;
}
BSTR bstrLogText;
bstrLogText = m_logtext.AllocSysString();
CString text((LPCWSTR)bstrLogText);
::AfxMessageBox(text);
if(FAILED(pITimeLog->OutputLog(&bstrLogText)))
{
::AfxMessageBox("日志输出出错!");
pITimeLog->Release();
return;
}
pITimeLog->Release();
::AfxMessageBox("日志已经写入!");
}
//释放组件
pIUnknown->Release();
pIUnknown = NULL;
::CoUninitialize();