What's the difference between CoCreateInstance() and CoGetClassObject() when creating objects on the same machine?

StackOverflow https://stackoverflow.com/questions/824907

Question

I understand that CoCreateInstance finds the COM server for the given class id, creates the object instance for that id and retrieves an interface from that object instance. CoGetClassObject() finds the COM server for the class id, creates an instance of the class factory for that class id and retrieves that class factory interface which can be then used for creating actual objects.

How else do these functions differ when used to create objects on the same machine? Do they work the same way but only cause different code to be invoked in the exactly same COM server?

Was it helpful?

Solution

CoGetClassObject essentially returns you a pointer to a factory for a particular interface. Under the hood, CoCreateInstance uses CoGetClassObject. The advantage of calling CoGetClassObject is that it allows you to only have to create the class factory once if you want to create many instances of a particular object.

The MSDN section on CoGetClassObject has a brief discussion on how you can take advantage of this functionality.

OTHER TIPS

One scenario in addition to what JaredPar said - CoGetClassObject returns you a class factory (calls DLLGetClassObject exported function of your DLL in case of inproc server). Class factory is used to instantiate coclass. CoCreateInstance internally calls CoGetClassObject, gets the required class factory and then uses it to instantiate the coclass you requested. When calling CoCreateInstance, you cannot delay creation of the coclass. There are times when creation of coclass could be expensive and you would want to delay its creation but still have access to the class factory so you could instantiate the coclass on demand.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top