Creating an Instance of a COM, a Bird’s Eye View

Let’s see, from a bird’s eye view, how the whole thing works. To get an interface to the ComInterface client, call:

IComInterface * pComInterface;
HRESULT hr= CoCreateInstance(CLSID_X, NULL,CLSCTX_ALL,IID_X,
                             (void**)& pComInterface);

if(hr == S_OK)
   hr = pComInterface ->method x;

Let’s see how this magical call to CoCreateInstance yields us the pointer to the interface, pComInterface, that we so dearly need.

CoCreateInstance calls:

CoGetClassObject(CLSID_X, CLSCTX_ALL /*dwClsContext*/, NULL, ,IID_X,
                 ,[out]pointer to X interface);

CoGetClassObject invokes the COM Service Control Manager, which searches in the Registry using the CLSID_X. It finds the associated ComServer DLL, loads it into memory, and calls the DllGetClassObject method of the DLL.

From the diagram above, it can be seen that the DLL contains an object of ComClassFactory. Also note that ComClassFactory inherits from IClassFactory and implements its methods, mainly CreateInstance.

The DllGetClassObject can be implemeted like this:

{

  ComClassFactory *pClassFactory ;
  pClassFactory = new ComClassFactory;

hresult = pClassFactory -CreateInstance(NULL, ,IID_X,
                                        [out]pointer to X interface)

}

From the diagram, you can see that ComClassFactory contains an object of ComClass.

Note that the ComClass inherits from IComInterface and implements all its methods. So, ComClassFactory :: CreateInstance(..) is implemented like so:

{

  ComClass *pComClass;
  pComClass = new ComClass;    // create a new object
  pComClass->QueryInterface( IID_X,[out]pointer to X interface)

Use the object pointer to call its implemented QueryInterface and return a pointer to the interface that we were seeking (one having IID_X). This is how we magically get our dear pointer to interface X.

Summary

CoCreateInstance(CLSID_X, NULL,CLSCTX_ALL,IID_X, (void**)&
                 pComInterface);

calls

CoGetClassObject(CLSID_X, CLSCTX_ALL /*dwClsContext*/, NULL, ,IID_X,
                 ,[out]pointer to X interface);

which calls SCM to search in the Registry for the location of the DLL using CLSID_X, loads the dll, and calls

DllGetClassObject(CLSID_X, ,IID_X, ,[out]pointer to X interface);

which creates an object of ComClassFactory:

ComClassFactory *pClassFactory ;
pClassFactory = new ComClassFactory;

and calls

hresult = pClassFactory -CreateInstance(NULL, ,IID_X,
                                        [out]pointer to X interface)

which creates an object of ComClass,

ComClass *pComClass;
pComClass = new ComClass;    // create a new object

and calls

pComClass->QueryInterface( IID_X,[out]pointer to X interface)

which gives us the pointer to the X interface that we so needed.

Alex C. Punnen

alexcpn@hotmail.com

More by Author

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Must Read