John Lam 1997 — 2026

RADICAL Automation: Dual Interfaces in Delphi 3

Since last year’s BDC, Borland has been hard at work making high-speed automation interfaces much easier to create in Delphi 3.0. Whereas last year I presented a straightforward way for you to create dual interface objects using Delphi 2.0, you still needed to know quite a bit about how the underlying COM mechanisms were making dual interfaces work for you. (For a quick review, see my PC Magazine article on Dual Interfaces and Delphi 2.0:

http://www.pcmag.com/issues/1519/pcmg0023.htm

You communicate with most traditional Automation objects through a mechanism known as late binding. Late binding allows a client application, otherwise known as an Automation controller, to call functions on an Automation object at run time without knowing anything at all about the Automation object. All of the binding is done at run time through a negotiation process that is quite similar to the process that is used to bind to dynamic link libraries via the LoadLibrary and GetProcAddress calls.

Automation objects that support dual interfaces, however, communicate through an early binding mechanism. The client application makes use of information that is provided by the creator of the Automation object to determine perform validation of function names and parameter types at compile time. Thus, this mechanism shifts the responsibility for binding to the compiler.

Early binding, as you might expect, is a far more efficient mechanism for communicating with an Automation object. However, what you must be aware of is that the only thing we are optimizing here is the speed of the actual function call. There is no optimization of the code on either side of the function call! In this paper I’ll present a sample application that graphically illustrates some of the performance implications of late binding vs. early binding.

A Quick Review of COM

Lets do a quick review of COM before we delve into the mysteries of dual interfaces. COM is the Component Object Model (not to be confused with the Common Object Model, which meant something different at one point in history, but has since been dropped). It is a specification for how objects can communicate and share information with each other at run-time. By adhering to this standard, which is a binary standard, you can create COM objects that can talk to any other COM object, independent of the programming language that was used to create them, and independent of the actual physical location of the object.

A COM object can be packaged inside a dynamic link library or an EXE file. COM objects that reside in DLL’s get loaded into the Win32 process of the code that is using that object. COM objects that reside in EXE’s execute within their own Win32 process. One of the key benefits of COM is that the caller does not care whether the object is in their own process space or another process space. This feature is called local-remote transparency, and it allows developers to leverage a given code base by allowing it to communicate to any object at any time, without the need to recompile their application’s code! The COM run-time libraries take care of all of the magic involved in making this happen in a process known as Marshalling.

You communicate with a COM object through one of its COM interfaces. A COM interface is a grouping of related functions, and is implemented as a table of pointers to those functions. This table is identical in structure to the v-tables used for dispatching virtual functions in both C++ and Delphi.

The user of a COM object can query a COM object for its interfaces, and when it finds one that it knows how to communicate with, it can establish a conversation with that COM object through that interface. Since COM interfaces are uniquely identified, it allows you to version a COM object’s functionality by introducing new interfaces that support the enhanced functionality, without sacrificing backwards compatibility with existing legacy code. Try doing that with DLL’s!

The COM interface that must be supported by all COM objects is called IUnknown. This ubiquitous interface is used to handle the two most important basic features of all COM objects: reference counting and interface querying. All COM objects are reference counted, to provide an automatic mechanism for managing their lifetimes. You can determine whether a COM object supports a given interface by calling its QueryInterface function. It either returns a reference to the requested interface or an error code if it doesn’t support that interface.

All other COM interfaces must derive from IUnknown. This way, the user of a COM object can always have access to the reference counting and interface querying functionality of a COM object without having to maintain a separate reference to a COM object’s IUnknown interface.

Late Binding and IDispatch

Late binding is implemented via a COM interface known as IDispatch. It is a COM interface that derives from IUnknown, and adds a number of additional functions:

function GetIDsOfNames(const IID: TGUID; Names: Pointer;

NameCount, LocaleID: Integer; DispIDs: Pointer): HResult; virtual; stdcall;

function GetTypeInfo(Index, LocaleID: Integer; out TypeInfo): HResult; virtual; stdcall;

function GetTypeInfoCount(out Count: Integer): HResult; virtual; stdcall;

function Invoke(DispID: Integer; const IID: TGUID; LocaleID: Integer;

Flags: Word; var Params; VarResult, ExcepInfo, ArgErr: Pointer): HResult; virtual; stdcall;

The GetIDsOfNames member function is used to resolve function names at run-time. By passing in the function name that you would like to bind to, GetIDsOfNames will return a dispatch ID that you can use to call the actual function in a subsequent call to Invoke.

The Invoke function is the workhorse of Automation. It allows you to call a function using its dispatch ID, and pass in an array of function parameters. These function parameters are all of a single known type called a VARIANT. VARIANTs can be used to hold any number of different parameter types, as is shown in the following list of legal types taken from the ActiveX.pas unit:

VT_EMPTY = 0; { [V] [P] nothing }

VT_NULL = 1; { [V] SQL style Null }

VT_I2 = 2; { [V][T][P] 2 byte signed int }

VT_I4 = 3; { [V][T][P] 4 byte signed int }

VT_R4 = 4; { [V][T][P] 4 byte real }

VT_R8 = 5; { [V][T][P] 8 byte real }

VT_CY = 6; { [V][T][P] currency }

VT_DATE = 7; { [V][T][P] date }

VT_BSTR = 8; { [V][T][P] binary string }

VT_DISPATCH = 9; { [V][T] IDispatch FAR* }

VT_ERROR = 10; { [V][T] SCODE }

VT_BOOL = 11; { [V][T][P] True=-1, False=0 }

VT_VARIANT = 12; { [V][T][P] VARIANT FAR* }

VT_UNKNOWN = 13; { [V][T] IUnknown FAR* }

VT_DECIMAL = 14; { [V][T] [S] 16 byte fixed point }

VT_I1 = 16; { [T] signed char }

VT_UI1 = 17; { [T] unsigned char }

VT_UI2 = 18; { [T] unsigned short }

VT_UI4 = 19; { [T] unsigned short }

VT_I8 = 20; { [T][P] signed 64-bit int }

VT_UI8 = 21; { [T] unsigned 64-bit int }

VT_INT = 22; { [T] signed machine int }

VT_UINT = 23; { [T] unsigned machine int }

VT_VOID = 24; { [T] C style void }

VT_HRESULT = 25; { [T] }

VT_PTR = 26; { [T] pointer type }

VT_SAFEARRAY = 27; { [T] (use VT_ARRAY in VARIANT) }

VT_CARRAY = 28; { [T] C style array }

VT_USERDEFINED = 29; { [T] user defined type }

VT_LPSTR = 30; { [T][P] null terminated string }

VT_LPWSTR = 31; { [T][P] wide null terminated string }

VT_FILETIME = 64; { [P] FILETIME }

VT_BLOB = 65; { [P] Length prefixed bytes }

VT_STREAM = 66; { [P] Name of the stream follows }

VT_STORAGE = 67; { [P] Name of the storage follows }

VT_STREAMED_OBJECT = 68; { [P] Stream contains an object }

VT_STORED_OBJECT = 69; { [P] Storage contains an object }

VT_BLOB_OBJECT = 70; { [P] Blob contains an object }

VT_CF = 71; { [P] Clipboard format }

VT_CLSID = 72; { [P] A Class ID }

VT_VECTOR = $1000; { [P] simple counted array }

VT_ARRAY = $2000; { [V] SAFEARRAY* }

VT_BYREF = $4000; { [V] }

VT_RESERVED = $8000;

VT_ILLEGAL = $ffff;

VT_ILLEGALMASKED = $0fff;

VT_TYPEMASK = $0fff;

Before a function call can take place, all of the function call parameters must first be converted into the VARIANT data type, which is a 16-byte packet of data. These VARIANT parameters are then assembled into an array of VARIANTS that are passed to the Automation object via the Invoke function call.

This early binding mechanism has a number of advantages. 1) At compile time, the caller does not need to know the names of the Automation object’s member functions. 2) At compile time, the caller does not need to know the detailed parameter lists of each function. 3) It is fairly straightforward for an Automation object to implement default parameters and optional parameters. However, this flexibility does not come without a cost.

Performance Implications

Before we look at the solution provided by dual interfaces, let’s take a look at how performance can be improved in the early binding mechanism.

By far the largest performance hit occurs when communicating with an Automation object that lives in another process space, or in another computer. Remember that under Win32 every process runs within the context of a protected address space that no other process can see. Therefore, passing parameters involves using some form of global memory buffer or some other type of messaging system to pass the actual parameters. Such processes are inevitably slow.

The best way of optimizing calls to Automation objects that reside outside of your process space is to reduce the number of round-trip calls that are required. Perhaps the most straightforward mechanism would be to cache the results of all calls to GetIDsOfNames after the initial call. Therefore instead of two round-trip calls to invoke a function (one to GetIDsOfNames and a subsequent one to Invoke), we can reduce it to a single call to Invoke.

However, since most Automation calls generally occur to objects that reside within our own process space, we will assume from this point onward that we will only be discussing calls to Automation objects that reside in our own process space.

How can we optimize the calls via Invoke for the in-process case? If we could somehow avoid the need for calling Invoke altogether, we could optimize the calls to the member functions of the Automation object. There is a significant performance penalty that is being paid in converting every parameter to a VARIANT before calling Invoke, and converting those parameters back into native data types on the Automation object’s side of the function call.

We can eliminate the need to convert arguments into arrays of VARIANTS if we could somehow create a specification that allows a caller to identify the function names and parameter types for all of the functions exported by an Automation object. This specification is known as a type library.

The importance of Type Libraries

Automation uses type libraries to identify an object’s capabilities. It lists, among other things, the interfaces supported by an object, the names and parameters of the member functions of each supported interface, and links to the appropriate help file topics.

A smart Automation controller can bind to an object’s type library to obtain, in one fell swoop, all of the information that it needs to implement early binding. Since it knows all of this information, it can avoid the need to convert to and from the universal VARIANT type and pass the native data types directly to the Automation object itself. It is the avoidance of this conversion process that is at the heart of the performance gains that can be realized through the use of dual interfaces.

As I mentioned earlier, custom COM interfaces are all derived from IUnknown. Dual interfaces, on the other hand, are all derived from IDispatch. This means that dual interfaces provide the caller with the flexibility of late binding via its GetIDsOfNames and Invoke functions, with the performance advantages of being able to call a function directly through its v-table offset.

However, to support both late and early binding, the parameters used in a dual-interface function must be automation compatible. This essentially means no user-defined types such as records. To pass a record to an Automation object, you must break up its data members into separate function parameters. This is a small price to pay for the universality that Automation brings to your objects.

Additional productivity features can also be implemented with the help of type libraries. Syntax checking, integration of the Automation object’s help files into the controller’s integrated development environment, and object browsing are among the many possible features that can be added.

What kind of performance increase can I get?

Performance is an elusive thing to measure in software. Mostly, it depends on the kind of Automation object that you are implementing. Remember that what we are optimizing by using dual interfaces is the amount of time that it takes for the actual function call itself.

You will get the greatest performance boost if the actual function call is a rate-determining step in your application. Typically, this case crops up when you are calling your Automation object within a very tight loop. If, on the other hand, you are calling a function that takes a long time to complete, you may see little or no performance improvement whatsoever.

An Overview of the ActiveX Enhancements in Delphi 3.0

Delphi 3.0 brings a number of very exciting enhancements to COM / Automation developers. They can be grouped into two general categories: 1) language enhancements in the form of native support for Automation and COM objects as native types and 2) visual tools that automate some of the more tiresome aspects of ActiveX programming.

The native support for COM interfaces and COM objects is one of the more exciting features of Delphi 3.0. Quite a few additions to the compiler and a host of supporting classes make creating COM objects very straightforward in Delphi.

You can declare a COM interface in Delphi 3.0 simply by using the new interface keyword:

IClassFactory = interface(IUnknown)

[‘{00000001-0000-0000-C000-000000000046}’]

function CreateInstance(const unkOuter: IUnknown; const iid: TIID;

out obj): HResult; stdcall;

function LockServer(fLock: BOOL): HResult; stdcall;

end;

You specify the COM interface’s IID (interface identifier) within the square brackets following the interface keyword.

When creating a COM object in Delphi 3.0, simply derive from TAutoObject or TComObject. Derive from TComObject if you want Delphi to automatically support the IUnknown interface for you. Derive from TAutoObject if you want Delphi to provide an implementation for IDispatch for you.

One of the greatest time saving devices in Delphi 3.0 is the ability to support multiple interfaces on a single COM object. This is accomplished through an extension to the class keyword. You can now derive from a single ancestor class, and implement one or more additional COM interfaces. For example:

TMyObject = class( TComObject, IShellExtInit, IPersistFolder, IShellFolder )

…

tells Delphi that you want to create a new COM object that implements the IShellExtInit, IPersistFolder and IShellFolder interfaces.

Deriving from TComObject instructs Delphi to provide a default implementation of IUnknown for you. In Delphi’s implementation of IUnknown, it will return the correct interface pointers for each of the 4 COM interfaces that are supported by TMyObject. TComObject also handles all of the reference counting details for you.

If you want to use a COM object, simply declare its interface as a variable. For example, if you wanted to create a COM object and manipulate it through its ISuperDuper interface, you’ll need to have two essential pieces of information. The first is the interface definition of ISuperDuper, and the second is the Class ID of the COM object that implements the ISuperDuper interface. Therefore, somewhere in your code you’ll have the interface declaration of ISuperDuper:

ISuperDuper = interface(IUnknown)

[‘{12345678-0000-0000-0000-CBA9876543210}’]

function DoSomethingSuper: HResult; stdcall;

function DoSomethingThatTakesAnArgument( const GoingIn: Integer; out ComingOut: IUnknown ): HResult; stdcall;

end;

To use ISuperDuper you’ll need to declare an interface reference variable:

var

SuperDuper: ISuperDuper;

To create an instance of ISuperDuper, you’ll need to have a declaration of the CLSID of the COM object that implements ISuperDuper:

const

CLSID_SuperDuperObject: TGUID = (

D1:$00000017;D2:$0000;D3:$0000;D4:($C0,$00,$00,$00,$00,$00,$00,$46));

The following line of code creates an instance of the ISuperDuper COM object, and assigns the value of the SuperDuper interface variable:

SuperDuper := CreateComObject( CLSID_SuperDuperObject );

If you browse through the comobj.pas file, you’ll see that CreateComObject is prototyped as:

functionCreateComObject(const ClassID: TGUID): IUnknown;

But how, you ask, does Delphi convert between IUnknown and ISuperDuper? Delphi generates an implicit QueryInterface call to obtain an ISuperDuper interface from the SuperDuperObject. The resolution of the interface occurs only at run-time, however, so this means that the compiler cannot detect an incompatible interface assignment at compile time.

One final note about interface reference variables: they are automatically resource protected. When an interface reference goes out of scope, it automatically calls Release on the object that it is currently assigned to before exiting.

Taken together, these interface reference variables combine many of the features that C++ developers have grown accustomed to with smart pointers. To summarize, interface reference variables will:

  • Release the COM object that they are assigned to when they go out of scope
  • convert between COM interfaces through implicit QueryInterface calls
  • Release the COM object that they are assigned to when they are re-assigned to another COM object

Delphi 3.0’s Type Library Editor and Two-way Tools Technology

Creating type libraries used to be an exercise in writing ODL (Object Definition Language) or IDL (Interface Definition Language) files. With Delphi 3.0’s new type library editor, creating type libraries is now a snap.

The major problem with type libraries in the past was that the tools used to create type libraries knew nothing about Pascal. They were primarily tools that were aimed at C and C++ developers, and contained a number of features that made their lives much easier. If you defined your interface in IDL, the midl.exe type compiler will emit the corresponding C/C++ header file declarations along with the binary type library file for your object(s).

Delphi 3.0 integrates the type library compiler into Delphi’s IDE. You can edit the type library using Delphi’s graphical type library editor, and synchronize the object with the underlying .pas file simply by clicking the Refresh button (Figure 1). This makes creating COM objects and their associated type library declarations a snap.

The code that the type library editor generates for you looks like regular Object Pascal code:

TTestObjectA = class(TAutoObject, ITestObjectA)

protected

procedure Proc1(var i: Integer); safecall;

end;

There’s also a hidden unit that contains most of the other declarations for your object. It has the same name as your type library (which defaults to your project’s name), but with a _TLB suffix appended to your name. It appears in your COM object’s uses clause, and by including this unit in your other Delphi units, you’ll get all of the requisite declarations for the object’s CLSID’s and its interface’s IID’s.

Building our Dual-Interface ActiveX Server

We will use Delphi 3’s new enhancements to build our dual interface ActiveX server:

  1. From the Object Repository, select New from the File menu.
  2. Click on the ActiveX tab and select ActiveX Library. Delphi will create a new ActiveX library module for you, with the appropriate files in the uses clause, and the correct functions exported.
  3. Go back to the ActiveX tab in the Object Repository and select ActiveX Object. Enter CalcObject as the name of the Automation object to create. Delphi will create a new skeleton ActiveX Object, as well as a default Type Library for your object. You should see the Type Library Editor displayed prominently in the foreground at this point.
  4. Click on the interface for ITCalcObject that was created for you by Delphi. If you examine its properties, you’ll see that its parent interface is IDispatch, indicating that it is declared as a dual interface Automation object.
  5. Start adding some new member functions to your project. In our case, we will add the following Method using the Type Library Editor: procedure AddOne(i: Integer; var iRet: Integer);- Click on the Type Library Editor’s Refresh button, and switch back to your unit’s code editor. - Enter the following implementation to the AddOne stub procedure that was generated for you by Delphi’s type library editor:

iRet := i + 1;

  • Compile your new Automation object, and select Register ActiveX Server from Delphi’s Run menu to register your Automation object.

As you can see, building dual interface Automation objects is only slightly more complicated than building a regular Delphi object. The only difference is that you enter the prototypes of your class’s member functions using the Type Library Editor rather than typing code into the interface section of your object’s unit.

Build and compile the test program (VDemo.dpr) for the Automation object that you just created. In the test program, I illustrate the two different mechanisms that you can use to create an instance of CalcObject in your Delphi applications:

FObj: ITCalcObject;

FDispObj: Variant;

…

if Dual then

FObj := CoTCalcObject.Create

else

FDispObj := CreateOleObject( ‘TCalcObject’ );

The instance of CalcObject that is created and assigned to FObj is a dual-interface Automation object. The instance of CalcObject that is created and assigned to FDispObj is a late-bound Automation object. The difference has to do with the variable types of FObj and FDispObj. FObj is an interface reference variable, and FDispObj is a general-purpose Delphi variant variable that implements Delphi’s generic Automation controller support.

If you run VDemo, and play around with the setting of the trackbar control, you’ll see some interesting behavior. VDemo creates two separate threads of execution. One uses the CalcObject object as a dual interface object, the other as a late-bound object.

The trackbar control adjusts the number of times that each thread calls its Automation object before advancing its progress meter. When the trackbar is set to a large value (to the right), you’ll see the most dramatic difference in speed between the dual interface automation object and the late-bound object. When the trackbar is set to a small number, you’ll see that eventually both threads will be executing at the same speed!

Wrapping things up

All Automation objects created using Delphi 3.0 will be dual-interface objects by default. By using Delphi’s built-in tools for creating and maintaining type libraries, you’ll find that creating Automation objects is a snap. Delphi’s native support for COM objects makes manipulating other people’s Automation objects very straightforward, and less error-prone than ever before.

Recommended Reading:

David Chappell, Understanding ActiveX and OLE: A Guide for Developers and Managers, Microsoft Press, 1996: an extremely good overview of the various ActiveX and OLE technologies.

Kraig Brockschmidt, Inside OLE 2nd Edition, Microsoft Press, 1995: the authoritative reference source.

Dale Rogerson, Inside COM, Microsoft Press, 1997: a very thorough explanation of the fundamental COM technologies.

Markus Horstmann, From C++ to COM, MSDN CD: one of the clearest treatments of the problems that COM was designed to solve-from the perspective of a C++ programmer.