Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 868
sharptooth Avatar asked May 05 '09 13:05

sharptooth


2 Answers

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.

  • http://msdn.microsoft.com/en-us/library/ms684007(VS.85).aspx
like image 187
JaredPar Avatar answered Oct 06 '22 17:10

JaredPar


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.

like image 42
byte Avatar answered Oct 06 '22 17:10

byte