views:

1262

answers:

2

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?

+3  A: 

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.

JaredPar
I've read that, but I don't see any benefits except for the CoGetClassObject() being potentially faster and the class factory object being able to persist state between CreateInstance() calls.
sharptooth
@sharptooth, that's pretty much the jist of it. Not much advantage at all which is why you rarely see it used.
JaredPar
Is there a chance that there's some other subtle difference like order of searching for dependencies? Do these functions work the same but just call different code in the same COM server?
sharptooth
@sharptooth, This is an area I haven't seriously played with in a year or two so my memory is not 100% fresh and I can't locate my trusty COM book right now. But from what I remember these two functions for a local COM server do the exact same thing. In fact, CoCreateInstance is typically just a wrapper around CoGetClassObject
JaredPar
A: 

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.

byte

related questions