# Automation in Delphi COM Programming

• Print

## In-Process Automation Servers

The first automation server we're going to develop is a simple in-process automation server. You should remember from Chapter 2 that in-process servers execute in the same address space as the client application.

### Example: Unit Conversion Server

This automation server will be able to convert between different area measurements. It can convert between square meters, square centimeters, square yards, square feet, square inches, square kilometers, square miles, and acres. You've already seen the method that will be responsible for the conversion, which appears as follows:

`function Convert(Quantity: Double; InUnit: Integer; OutUnit: Integer): Double; safecall;`

In a nutshell, Convert converts a given quantity from the unit of measure designated by InUnit to the unit of measure designated by OutUnit. The actual code that performs the conversion is quite simple, and is shown in the following example:

```const
auSquareMeters = \$00000000;
auSquareCentimeters = \$00000001;
auSquareYards = \$00000002;
auSquareFeet = \$00000003;
auSquareInches = \$00000004;
auSquareKilometers = \$00000005;
auSquareMiles = \$00000006;
auAcres = \$00000007;
function TUnitAuto.Convert(Quantity: Double; InUnit,
OutUnit: Integer): Double;
const
AreaFactor: Array[auSquareMeters .. auAcres] of Double =
(10000.0, 1.0, 8361.2736, 929.0304, 6.4516, 10000000000.0,
25899881103.4, 40468726.0987);
begin
Result := Quantity * AreaFactor[InUnit] / AreaFactor[OutUnit];
end;```

The AreaFactor array contains the factors necessary to convert between a given unit of measure and square centimeters. For example, one square meter is 10,000 square centimeters, and one acre is 40,468,726.0987 square centimeters. The Convert function simply converts from InUnit to square centimeters, and then from square centimeters to the OutUnit.

Now that you know how the process works, let's create an automation server to expose this functionality.

1. Select File, New from Delphi's main menu. In the ActiveX tab of the Object Repository, select the ActiveX Library icon. So far, the steps are identical to those we took when we created an in-process COM server.

2. Select File, New from the main menu again, and in the ActiveX tab of the Object Repository, select Automation Object. Delphi displays the Automation Object Wizard, shown in Figure 4.2.

Figure 4.2
The Automation Object Wizard.

1. Enter a Class Name of AreaUnitConverter, and click OK. Delphi creates a unit for the class, and also creates a type library. The type library editor will automatically be displayed.

2. Click IAreaUnitConverter in the Object List. Notice in the Information Pane that the IAreaUnitConverter interface descends from IDispatch (Figure 4.3).

We already know what the Convert method needs to do, so let's add it to the interface.

Figure 4.3
The Type Library Editor.

1. Click the New Method icon on the toolbar, and name the method Convert. Notice that in the Information Pane, Delphi has assigned a dispid of 1 to this method.

2. Click the Parameters tab, and set the Return Type to Double. Now add a parameter named Quantity, of type Double. Add an Integer parameter named InUnit and another Integer parameter named OutUnit.

When you're finished, your screen should look like Figure 4.4.

Now, rather than forcing users of this automation server to remember that 0 means square meters and so on, let's add an enumeration to the type library.

Figure 4.4
The Type Library Editor after adding a method.

1. Click the New Enumeration button on the toolbar. Name the enumeration AreaUnit. Now click the NewConst button and add a constant named auSquareMeters. Do the same for auSquareCentimeters, auSquareYards, auSquareFeet, auSquareInches, auSquareKilometers, auSquareMiles, and auAcres. Delphi will automatically assign the values zero through seven to the enumeration constants.

2. Click the Refresh Implementation button on the type library toolbar to ensure that the Delphi code reflects the additions made to the type library. You can now close the Type Library Editor.

3. Save the Delphi unit as AreaUnit.pas, and the project as UnitSrv.dpr. Now flesh out the Convert method so it appears as follows:

```function TUnitAuto.Convert(Quantity: Double; InUnit,
OutUnit: Integer): Double;
const
AreaFactor: Array[auSquareMeters .. auAcres] of Double =
(10000.0, 1.0, 8361.2736, 929.0304, 6.4516, 10000000000.0,
25899881103.4, 40468726.0987);
begin
Result := Quantity * AreaFactor[InUnit] / AreaFactor[OutUnit];
end;```

That's all we need to do for this server. Compile it to make sure you didn't make any typos, and then select Run, Register ActiveX Server to register the server with the Windows registry.

I'm not going to bother listing the source code for the server, because you've already seen most of it, and what you have not seen, Delphi automatically created for you. Now we can concentrate on writing a client application to access the server.

Note - You might be thinking that this process seemed entirely too easy. We didn't even press Ctrl+Shift+G to generate a GUID for the IAreaUnitConverter interface. The fact is that we've done all the work required to write a dual-interface automation server. Delphi's wizard automatically generated the necessary GUIDs for us.

You might have noticed that it was even easier to create this COM automation server than it was to create the plain COM servers in Chapter 2. When I write COM code, I almost always create automation servers. They're a snap to create, and they're much more flexible than standard COM objects.

### CreateOleObject and GetActiveOleObject

Earlier, I showed you how CreateOleObject is used to start a new instance of an automation server. CreateOleObject is declared in the file comobj.pas as follows:

```function CreateOleObject(const ClassName: string): IDispatch;
var
ClassID: TCLSID;
begin
ClassID := ProgIDToClassID(ClassName);
OleCheck(CoCreateInstance(ClassID, nil, CLSCTX_INPROC_SERVER or
CLSCTX_LOCAL_SERVER, IDispatch, Result));
end;```

As you can see, this function first obtains the GUID of the class that we're creating. Then, it passes that GUID to CoCreateInstance. I discussed CoCreateInstance in Chapter 2. ProgIDToClassID is basically a wrapper around the Windows API called CLSIDFromProgID. So, in a nutshell, CreateOleObject works similarly to CreateComObject, except CreateOleObject takes a class name as a parameter instead of a GUID.

However, CreateOleObject always creates a new instance of a given server. What if you want to connect to an already running instance of a server? Or maybe you do not know whether the server is running or not. You'd like to start it if it is not running, and connect to it if it is.

GetActiveOleObject can be used to obtain a reference to a server that is running in memory. In Chapter 2, I discussed the Running Object Table in Windows, which tracks all active COM objects. GetActiveOleObject looks in the Running Object Table to see if the given server is running. If it is, it returns a reference to the IDispatch interface on that server. If the server is not running, GetActiveOleObject raises an exception.

With that information in mind, the following procedure will start a new copy of Word if it isn't running, and will connect to an already-running copy if it is:

```procedure StartOrLinkToWord;
var
V: Variant;
begin
try
V := GetActiveOleObject('Word.Basic');
except
V := CreateOleObject(Word'.Basic');
end;

// Do something with V here...
end;```

### Example: Unit Conversion Client

Now we can concentrate on writing a client program to access the automation server we just created. Figure 4.5 shows the main form of the UnitCli application at runtime.

As you can see, this program's interface is composed of six buttons. The left column of buttons creates and accesses the automation server in each of the three possible ways: by interface, by variant, and by dispinterface. The right column of buttons operates the same as the left column, except it makes 100,000 calls in a row for timing purposes.

Figure 4.5
UnitCli performs time tests on interfaces, dispinterfaces, and variants.

The code required to access the server is small, in all three cases. Let's view an example of the code for accessing the server through an interface first.

```procedure TForm1.btnInterfaceClick(Sender: TObject);
var
I: IUnitAuto;
begin
I := CoUnitAuto.Create;
ShowMessage(FloatToStr(I.Convert(1.0, auSquareMeters, auSquareCentimeters)));
end;```

You've seen similar code in Chapter 2. The call to CoUnitAuto creates an instance of the automation server, and I.Convert converts 1.0 square meters to square centimeters. Do not forget that due to reference counting, the server is automatically destroyed at the end of the procedure.

Now let's look at accessing the same server through a variant.

```procedure TForm1.btnVariantClick(Sender: TObject);
var
V: Variant;
begin
V := CreateOleObject('UnitSrv.UnitAuto');
ShowMessage(FloatToStr(V.Convert(1.0, auSquareMeters, auSquareCentimeters)));
end;```

This code is very similar to the code required to access the server through an interface. The first line of code makes a call to CreateOleObject to create an instance of the server. You're probably wondering how I knew to use UnitSrv.UnitAuto as the class name to pass to CreateOleObject. Delphi creates this string for you by concatenating the name of the server, a dot, and the name of the CoClass. For reference, the type library for the UnitSrv server is shown in Figure 4.6.

As you can see, the name of the library is UnitSrv. The CoClass is highlighted in the Object List, and is named UnitAuto. Therefore, the classname for the object is UnitSrv.UnitAuto.

A second method you can use to determine the class name of the server is to look up the GUID in the Windows Registry. The GUID for UnitAuto is {A1E420C3-F75F-11D2-B3B9-0040F67455FE}. In the Registry, you'll see an entry like that shown in Figure 4.7.

Figure 4.6
UnitSrv type library.

Figure 4.7
UnitAuto entry in RegEdit.

You cannot use these methods if you are using somebody else's automation server that might not have been created in Delphi, or if you do not know the GUID of the object in question. In those cases, the documentation for that server should give you the class name(s) available for you to use.

After CreateOleObject works its magic and stores a reference to the automation server in the variant V, we can make calls to that server just as if we were using an interface. As I explained before, the internal mechanism for making variant calls is considerably different (and slower) than that used for interfaces.

The final method for accessing the automation server is through a dispinterface.

```procedure TForm1.btnDispInterfaceClick(Sender: TObject);
var
DI: IUnitAutoDisp;
begin
DI := CoUnitAuto.Create as IUnitAutoDisp;
ShowMessage(FloatToStr(DI.Convert(1.0, auSquareMeters, auSquareCentimeters)));
end;```

As you can see, this code is almost identical to the code used for interfaces. The only difference is that the interface obtained through CoUnitAuto.Create is converted to a dispinterface.

Listing 4.1 shows the code for the main form of the client application.

#### Listing 4.1  UnitCli Application—MainForm.pas

```unit MainForm;

interface

uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls;

type
TForm1 = class(TForm)
btnVariant: TButton;
btnInterface: TButton;
btnDispInterface: TButton;
btnTimeInterface: TButton;
btnTimeVariant: TButton;
btnTimeDispInterface: TButton;
lblInterface: TLabel;
lblVariant: TLabel;
lblDispInterface: TLabel;
procedure btnVariantClick(Sender: TObject);
procedure btnInterfaceClick(Sender: TObject);
procedure btnDispInterfaceClick(Sender: TObject);
procedure btnTimeInterfaceClick(Sender: TObject);
procedure btnTimeVariantClick(Sender: TObject);
procedure btnTimeDispInterfaceClick(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;

var
Form1: TForm1;

implementation

uses
ComObj, UnitSrv_TLB;

{\$R *.DFM}

procedure TForm1.btnV
ariantClick(Sender: TObject);
var
V: Variant;
begin
V := CreateOleObject('UnitSrv.UnitAuto');
ShowMessage(FloatToStr(V.Convert(1.0, auSquareMeters, auSquareCentimeters)));
end;

procedure TForm1.btnInterfaceClick(Sender: TObject);
var
I: IUnitAuto;
begin
I := CoUnitAuto.Create;
ShowMessage(FloatToStr(I.Convert(1.0, auSquareMeters, auSquareCentimeters)));
end;

procedure TForm1.btnDispInterfaceClick(Sender: TObject);
var
DI: IUnitAutoDisp;
begin
DI := CoUnitAuto.Create as IUnitAutoDisp;
ShowMessage(FloatToStr(DI.Convert(1.0, auSquareMeters, auSquareCentimeters)));
end;

procedure TForm1.btnTimeInterfaceClick(Sender: TObject);
var
I: IUnitAuto;
Count: Integer;
Dbl: Double;
T1, T2: DWord;
begin
I := CoUnitAuto.Create;
T1 := GetTickCount;
for Count := 1 to 100000 do
Dbl := I.Convert(1.0, 0, 1);
T2 := GetTickCount;
lblInterface.Caption := IntToStr(T2 - T1) + ' ms';
end;

procedure TForm1.btnTimeVariantClick(Sender: TObject);
var
V: Variant;
Count: Integer;
Dbl: Double;
T1, T2: DWord;
begin
V := CreateOleObject('UnitSrv.UnitAuto');
T1 := GetTickCount;
for Count := 1 to 100000 do
Dbl := V.Convert(1.0, auSquareMeters, auSquareCentimeters);
T2 := GetTickCount;
lblVariant.Caption := IntToStr(T2 - T1) + ' ms';
end;

procedure TForm1.btnTimeDispInterfaceClick(Sender: TObject);
var
DI: IUnitAutoDisp;
Count: Integer;
Dbl: Double;
T1, T2: DWord;
begin
DI := CoUnitAuto.Create as IUnitAutoDisp;
T1 := GetTickCount;
for Count := 1 to 100000 do
Dbl := DI.Convert(1.0, auSquareMeters, auSquareCentimeters);
T2 := GetTickCount;
lblDispInterface.Caption := IntToStr(T2 - T1) + ' ms';
end;

end.```

This application can access our server either through an interface, a dispinterface, or IDispatch. A real application would simply choose one of the three methods. My purpose in showing all three methods is two-fold:

1. I want you to see how to use each method in your own applications.

2. This program performs some timing tests to show you the relative times for each method.

If you'll refer back to Figure 4.5, you'll see the timing results on my own computer. These values represent the time required to call the Convert method 100,000 times.

As you can see, interfaces are by far the fastest way to call a method on an automation server. Variants are more than an order of magnitude slower, and dispinterfaces lie somewhere in between.

By now, you should be familiar with in-process Automation servers. However, in-process Automation servers are not always appropriate. If you want to create COM servers that run in a separate address space from the client application, you'll need to create an out-of-process Automation server. The next section will guide you through the creation and uses of out-of-process Automation servers.