I am attempting to understand creating/using COM components without the help of MFC/ATL to know its inner workings. I am using this codeguru article for reference.Following are the steps followed by me.
- Created a Wind32 Dll,
- Added a MIDL file and declared the interface
IAddand library nameDemoMath; compiled the code using MIDL compiler. - Created
CAddObjclass derivingIAddinterface,provided implementation forIAddandIUnknowninterfaces. - Created class
CAddFactoryderiving fromIClassFactoryinterface;provided implementation forIClassFactorymethods.
Now creating DllGetClassObject to give client an option to invoke this function to get an instance of the class factory.
Following is the code:
#include "stdafx.h"
#include <objbase.h>
#include "AddObjFactory.h"
#include "IAdd_i.c"
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;
}
Now where is CLSID_AddObject constant suppose to be defined
or Is it generated while compiling MIDL file(I didn't find it though)?
newreturned zero on failure. However, that hasn't been the case for over a decade, even on Microsoft's compilers. You need to catch thestd::bad_allocexception instead.DllGetClassObject()implementation.QueryInterface()increments the reference count if successful. If failed, your object does not get freed. You should start the object with a reference count of 1, callQueryInterface()on it, and then callRelease()on it regardless of whetherQueryInterface()succeeds or fails. That way, if successful, the reference count is only 1 (in the caller) whenDllGetClassObject()exits, and if failed then the object gets freed correctly.