Finally i got some time to understand the core of COM. I started with the “Inside COM”by Dale Rogerson (http://www.amazon.com/Inside-Microsoft-Programming-Dale-Rogerson/dp/1572313498). It is one of the best book to understand COM. COM Spec is around 256 pages. We use COM to break an application into multiple components. In many ways, it helps the software developers Eg. during software update.
What is COM ?
COM is the foundation on which M$ technologies such as ActiveX, DirectX and OLE are built.
COM is a binary specification.
COM is not a big API.
COM is a way to program in much the same way that structured programming and Object Oriented programs are ways to program.
COM components are fully language independent. (Client/server should not worry about the language used to implement other side)
In COM, “Interfaces” are everything.
For COM, an interface is a specific memory structure containing an array of function pointers.
COM should be shipped in binary form.
There is a common misconception that COM should be written in C++. C++ makes it easier. Other than that you can write it in any language of your choice.
DLL is not COM.
Lets clear the basic confusion now….
A DLL can host any number of components.
A component can support any number of interfaces.
An interface can provide any number of function.
How is that interface’s memory structure looks like ?
COM requires all interfaces to support three functions. What does it really mean ? First three functions in the array of function pointers should be same for all three interfaces. In the above figure, rightmost table should have these three functions as initial entries.
So, what is the use of these three functions. QueryInterface() helps “client” to locate other interfaces supported by the component. AddRef()/Release() are there for component lifetime management. All these three functions are grouped as “IUnknown” Interface. So any COM interface can be casted as “IUnknown” pointer. This is a very important concept. You can say QueryInterface() is one of the most important function in the IUnknown. Others are also important but QueryInterface() is core of all. There are some rules and regulations for QueryInterface().
Rules and Regulations for QueryInterface(): (without this COM will not function properly)
You always get the same IUnknown
You can get an interface if you got it before.
You can get the interface you have.
You can always get back to where you started.
You can get there from anywhere if you can get there from somewhere.
Rules and Regulations for AddRef()/Release():
Call AddRef() before returning.
Call Release() when you are done.
Call AddRef() after assignment.