Construct a minimum framework structure for creating COM components, and then take a look at the internal processing process.
Iunknown * punk = NULL;
Iobject * pobject = NULL;
Coinitialize (null );
Cocreateinstance (clsid_object, clsctx_inproc_server, null, iid_iunknown, (void **) & punk );
Punk-> QueryInterface (iid_iojbect, (void **) & pobject );
Punk-> release ();
Pobject-> func ();
Pobject-> release ();
Couninitialize ();
This is a typical framework for creating COM components, but I am interested in cocreateinstance. Let's take a look at what it has done internally. The following is a pseudo code implemented internally:
Cocreateinstance (....)
{
.......
Iclassfactory * pclassfactory = NULL;
Cogetclassobject (clsid_object, clsctx_inproc_server, null, iid_iclassfactory, (void **) & pclassfactory );
Pclassfactory-> createinstance (null, iid_iunknown, (void **) & punk );
Pclassfactory-> release ();
........
}
In this section, the class factory object is obtained first, and then the class factory creates components to obtain the iunknown pointer. Take a further step and check the internal pseudo code of cogetclassobject:
Cogetclassobject (.....)
{
// Query the Registry clsid_object to find the location and file name of the component DLL.
// Load the dll library
// Use the getprocaddress (...) function to obtain the function pointer of the dllgetclassobject function in the dll library.
// Call dllgetclassobject
}
What is dllgetclassobject? It is used to obtain the class factory object. Only the class factory can be used to create components.
The following is the pseudo code of dllgetclassobject:
Dllgetclassobject (...)
{
......
Cfactory * pfactory = new cfactory; // class factory object
Pfactory-> QueryInterface (iid_iclassfactory, (void **) & pclassfactory );
// Query the iclassfactory pointer
Pfactory-> release ();
......
}
The cogetclassobject process has reached this point. Now return cocreateinstance and check the pseudo code of createinstance:
Cfactory: createinstance (.....)
{
...........
Cobject * pobject = new cobject; // Component Object
Pobject-> QueryInterface (iid_iunknown, (void **) & punk );
Pobject-> release ();
...........
}