Basic COM   «Prev  Next»
Lesson 9 COM clients - Creating COM objects
Objective Learn how a COM client gets a class factory and creates an instance of COM object, getting its first interface pointer into the object.

Creating COM Objects

A COM server and its objects do not stand alone. They exist to provide services to COM clients. A COM application contains both clients and servers.
Before accessing any COM services a client must call COM function CoInitialize(NULL). This call must be made in each client thread that accesses COM! For now we will only deal with single-threaded clients.
After calling CoInitialize a client gets class factories, one for each type of COM object it wants to use, by calling CoGetClassObject. The following Slideshow will step you through this process.

1) Object Class Factory1 2) Object Class Factory2 3) Object Class Factory3 4) Object Class Factory4 5) Object Class Factory5

Program 1 Program 2 Program 3 Program 4 Program 5
StdApi CoGetClassObject
Once a client has an IClassFactory pointer, it can call IClassFactory::CreateInstance to create an instance of the COM object and get its first interface pointer into the object. When finished using the IClassFactory pointer, a client calls IClassFactory::Release.
COM provides helper function CoCreateInstance, which calls CoGetClassObject, IClassFactory::CreateInstance, and IClassFactory::Release.

Call CoCreateInstance

Clients that need to create only one instance of a particular COM object call CoCreateInstance. To support calling
  1. CoGetClassObject and
  2. IClassFactory::CreateInstance,
  3. CoCreateInstance
combines parameters used in both calls:

STDAPI CoCreateInstance(
           REFCLSID rclsid,     
           LPUNKNOWN pUnkOuter, 
           DWORD dwClsContext,  
           REFIID riid,         
           LPVOID * ppv);

CoCreateInstance versus CoGetClassObject

CoCreateInstance has one limitation when compared to CoGetClassObject. It does not take an IID to specify which object creation interface to get. Recall that a class factory is a "type of" class object that implements interface IClassFactory. CoCreateInstance assumes the client wants an IClassFactory interface and the object's class object is a class factory. Although this is OK for the majority of COM objects, occasionally a COM object supports a different object creation interface. You must use CoGetClassObject to get an object creation interface for class objects that do not implement IClassFactory.
For this course, all our class objects will be class factories, that is they support IClassFactory.

After releasing its COM interface pointers, a client calls CoUninitialize() to tell COM that its thread will no longer access COM services or COM objects.

Accessing Com Objects - Quiz

Click the Quiz link below to check your understanding of how COM objects are accessed.
Accessing Com Objects - Quiz