Interfaces

A COM component exposes sets of methods and fields through one or more interfaces. The term “expose” means to define an object field or method so that it is visible outside the component’s definition. For example, the public methods and fields of a Java class define the interface that the class exposes for use by outside classes. But not all Java classes are COM objects; the operating system must be made aware of the interface and be told how to run the associated code. That is accomplished with an Object Description Language (ODL) file that describes the interfaces for COM objects. Each ODL description compiles into a type library (TLB) file containing information about the component’s interfaces. When a new COM component is added to your system, an entry describing the methods and fields exposed by the new object type will be created in the system registry. Type libraries will be discussed a bit more in subsequent chapters.

All interfaces for COM objects are subclasses of IUnknown, which defines three universal interface methods: QueryInterface, AddRef, and Release. The first of these, QueryInterface, allows the user of an interface to use an interface-specific ID code to request a pointer to a different interface on that object. However, an object does not have to provide references to all of its interfaces through QueryInterface. For example, you might want to keep private an interface used only to debug code, or your company might want to limit access to a proprietary interface included in an otherwise public COM component.

The AddRef and Release methods together provide a rudimentary mechanism for garbage collection among COM components. However, the removal of unused components isn’t automatic. COM was designed to produce small, fast components, so the elimination of unnecessary components was left as a manual process. Whenever you create an interface reference, you should call AddRef to increment a reference count for that interface. When an interface is no longer needed, make a call to Release to decrement the reference count. If the reference count for each of its interfaces is 0, the component knows that it is no longer being accessed and can remove itself from memory.

In some implementations, AddRef and Release manage a reference count for the entire object instead of each interface; a 0 reference count causes the removal of the object.

© 1997 by Scott Ladd. All rights reserved.