在VC++6.0中用MFC进行COM编程(4)
//实现接口ITimeLog方法
STDMETHODIMP
CTimeLogServer::XTimeLog::OutputLog(BSTR* varLogText)
{
METHOD_PROLOGUE(CTimeLogServer,TimeLog)
if(pThis->;m_logfile)
{
CTime TimeStamp = CTime::GetCurrentTime();
CString NowTime = TimeStamp.Format(";%Y年%m月%d日%H:%M:%S";);
CString LogText((LPCWSTR)*varLogText);
fprintf(pThis->;m_logfile,";
%s
%s
%";,NowTime,LogText);
return NOERROR;
}
else
{
AfxMessageBox(";没有日志文件!";);
return S_FALSE;
}
}
七.完善组件服务器
在应用对象CTimeLogServerApp的 实现文件中,处理Instance()和ExitInstance()
BOOL CTimeLogServerApp::InitInstance()
{
::AfxOleLockApp();
// Register all OLE server (factories) as running. This enables the
// OLE libraries to create objects from other applications.
COleObjectFactory::RegisterAll();
return TRUE;
}
int CTimeLogServerApp::ExitInstance()
{
// TODO: Add your specialized code here and/or call the base class
::AfxOleUnlockApp();
return 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();