类厂是COM对象的生产基地,COM库通过类厂创建COM对象。在这里,我们需要实现一类厂来创建COPCServer类的对象。
添加新类CBSClassFactory,继承IClassFactory接口,头文件内容如下:
|
CBSClassFactory类要实现IUnknown接口函数和IClassFactory接口函数,同时添加两个函数RegisterClassObject()和RevokeClassObject()。
下面介绍几个主要函数:
1. QueryInterface
2. AddRef
// This class is singleton, so just return a constant STDMETHODIMP_(ULONG) CBSClassFactory::AddRef(void) { return 2; } |
3. Release
// This class is singleton, so just return a constant STDMETHODIMP_(ULONG) CBSClassFactory::Release(void) { return 1; } |
4. CreateInstance
STDMETHODIMP CBSClassFactory::CreateInstance(IUnknown *pUnkOuter, REFIID riid, void **ppv) { *ppv = 0; // can't aggregate an out of process object if (pUnkOuter) return CLASS_E_NOAGGREGATION; COPCServer* pServer = new CComObject<COPCServer>; if (pServer == NULL) return E_OUTOFMEMORY; HRESULT hr = pServer->QueryInterface(riid, ppv); return hr; } |
5. RegisterClassObject
6. RevokeClassObject
void CBSClassFactory::RevokeClassObject(void) { CoRevokeClassObject(m_dwReg); } |
3.2 使用CBSClassFactory
在BSOPCServer.cpp中定义全局类工厂实例;
CBSClassFactory* g_pPrivateFactory = NULL;
在BSOPCServer.cpp中,函数CBSOPCServerApp::InitInstance(),
将下面的代码稍作修改:
if (FAILED(_AtlModule.RegisterClassObjects(CLSCTX_LOCAL_SERVER, REGCLS_MULTIPLEUSE)))
return FALSE;
替换成:
if (g_pPrivateFactory == NULL)
{
g_pPrivateFactory = new CBSClassFactory();
if (FAILED(g_pPrivateFactory->RegisterClassObject()))
{
TRACE("Register Class Object failed.");
return FALSE;
}
}
函数CBSOPCServerApp::ExitInstance(void)中,将
_AtlModule.RevokeClassObjects();
替换成:
if (g_pPrivateFactory != NULL)
{
g_pPrivateFactory->RevokeClassObject();
delete g_pPrivateFactory;
g_pPrivateFactory = NULL;
}
到这里为止,创建类厂的工作基本完成。