Summarize the code implemented in this article into a single project. At present, it is only implemented to an intermediate stage, focusing on the implementation principle of COM interface, and does not include the part of the class factory. In the future, we need to add advanced functions such as plant.
File composition:
Ifoo.h COM interface IFoo, interface ID iid_ifoo declaration file.
outside.c COM interface implementation. The implementation of IFoo here is a structural body coutside.
UTIL.H some macro definitions, global functions, variable declaration files.
Main.c the author for the implementation of the project added files. Provides implementations of the main function, memory management function Alloc,free (encapsulating C run-time Library functions malloc and free.), interface ID definitions.
What exactly is a COM interface?
A COM interface is a pointer to a virtual function table. This pointer allows you to access individual blocks of functionality somewhere in memory, perform predefined functions, and complete the user's tasks. These blocks of functionality exist in the form of functions (no other form can be found:) and are invoked. They all have one thing in common: they all contain a pointer parameter that points to the data address that these features want to manipulate. In C + +, this address is the first address of an object, which is the implied this pointer in a class member function. This is not readily available in the C function, so the interface pointer (HRESULT (__stdcall * QueryInterface) (IFoo * This, const IID * const, void * *) is still used in the code implementation while the interface is defined, and When the interface function is implemented, the object instance pointer is calculated from this interface pointer according to the structure of the structural body layout.
typedef struct IFoo
{
struct IFooVtbl * lpVtbl;
} IFoo;
typedef struct IFooVtbl IFooVtbl;
struct IFooVtbl
{
HRESULT (__stdcall * QueryInterface) (IFoo * This, const IID * const, void **) ;
ULONG (__stdcall * AddRef) (IFoo * This) ;
ULONG (__stdcall * Release) (IFoo * This) ;
HRESULT (__stdcall * SetValue) (IFoo * This, int) ;
HRESULT (__stdcall * GetValue) (IFoo * This, int *) ;
};
Requirements for COM interfaces:
The first three functions of each COM interface (point to a virtual function table) must be functions of the IUnknown interface: Queryinterface,addref and release. In C + +, it is called inherit from the IUnknown interface.
All interfaces implemented by the same object must be the same for the interface pointer value obtained by invoking the QueryInterface response query Iid_iunknwon. This is the standard for determining whether two COM objects are the same object.
Macro definition "#define IUNK_VTABLE_OF (x) ((IUNKNOWNVTBL *) ((x)->lpvtbl))" description