|
第七步 实现IClassFactory的方法
实现类CAddFactory的方法。创建一个新文件(AddObjFactory.cpp)。提供类IUnknown和IClassFactory的方法实现。AddRef,Release和QueryInterface方法实现和前面类CAddObj中这三个函数实现基本一样。在方法CreateInstance中,类CaddObj被实例化并且传回其接口指针。LockServer方法没有给出细节的实现。
HRESULT __stdcall CAddFactory::CreateInstance(IUnknown* pUnknownOuter,
const IID& iid,
void** ppv)
{
//
//This method lets the client manufacture components en masse
//The class factory provides a mechanism to control the way
//the component is created. Within the class factory the
//author of the component may decide to selectivey enable
//or disable creation as per license agreements
//
//
// Cannot aggregate.
if (pUnknownOuter != NULL)
{
return CLASS_E_NOAGGREGATION ;
}
//
// Create an instance of the component.
//
CAddObj* pObject = new CAddObj ;
if (pObject == NULL)
{
return E_OUTOFMEMORY ;
}
//
// Get the requested interface.
//
return pObject->QueryInterface(iid, ppv) ;
}
HRESULT __stdcall CAddFactory::LockServer(BOOL bLock)
{
return E_NOTIMPL;
}
/////////////////////////////////////////////////////////////////
第八步 实现DllGetClassObject的方法
一个进程内COM对象只是一个简单的WIN32DLL,他遵循既定的协议。每一个COM DLL必须有一个通过名字DllGetClassObject的出口函数。客户端将调用这个函数以得到类厂的接口(IUnknown or IClassFactory),之后就是调用CreateInstance方法。创建一个新文件(Exports.cpp),在其中实现DllGetClassObject。(代码如下)
STDAPI DllGetClassObject(const CLSID& clsid,
const IID& iid,
void** ppv)
{
//
//Check if the requested COM object is implemented in this DLL
//There can be more than 1 COM object implemented in a DLL
//
if (clsid == CLSID_AddObject)
{
//
//iid specifies the requested interface for the factory object
//The client can request for IUnknown, IClassFactory,
//IClassFactory2
//
CAddFactory *pAddFact = new CAddFactory;
if (pAddFact == NULL)
return E_OUTOFMEMORY;
else
{
return pAddFact->QueryInterface(iid , ppv);
}
}
//
//if control reaches here then that implies that the object
//specified by the user is not implemented in this DLL
//
return CLASS_E_CLASSNOTAVAILABLE;
}
/////////////////////////////// [1] [2] 下一页 |