I'm a .NET programmer and new to COM. Would like to know in simple terms what is the function of CoCreateInstance?
Put simply, it's used to create an instance of a class, the class being specified by a GUID.
HRESULT CoCreateInstance(
__in REFCLSID rclsid, // which class you want
__in LPUNKNOWN pUnkOuter, // used in aggregation
__in DWORD dwClsContext, // how/where you want the object created
__in REFIID riid, // which of the object's interfaces you want to use
__out LPVOID *ppv // where the pointer to the created object is placed
);
For more info, read the documentation.
You can think of CoCreateInstance()
as an interface to an anonymous factory class.
In OOP it's often reasonable to use a factory pattern to just call a creation method and get an interface pointer/reference without having to know what class exactly is behind that interface. But you still need to know which class to use as a factory. You might hide that too by having some global function but you would still need to know its name and calling conventions.
CoCreateInstance goes further - it hides the factory class as well and provides a system-wide global function. All you provide it are a class id - which is just a GUID - and an interface id - which is also a GUID. You don't know where the implementation is and what language it is in - COM deals with all that given that there is a COM server on your system that contains the implementation for the specified class id that exposes an interface for the specified interface id.
You call system-wide global CoCreateInstance(), it finds the COM server (or fails), initializes it, asks it to create an object (might fail), retrieves an interface pointer to that object (might fails as well) and returns this interface pointer to you.