Writing DLLs in Delphi

A DLL Example for Numbers

The easiest DLL procedures and functions to write are those that transfer numbers either integer, or floating point. The Delphi test project file demonstrates the Delphi and VB declarations required:

  program Rg;
  uses
    Forms,
    Rg1 in 'RG1.PAS' {Form1},
    Rg2 in 'RG2.PAS';{$R*.RES}
  begin
  Application.CreateForm(TForm1, Form1);
    Application.Run;
  end.

The unit containing the DLL code is shown below. Notice the declaration in the interface section and the use of the export directive after the declaration. The export directive makes a procedure or function within a DLL exportable by forcing the routine to use the far call model and generating special procedure entry and exit code.

  unit Rg2;
  interface
  procedure ChangeInt(x1 : integer; var x2 : integer); export;    
                                        {Note export directive}
  procedure ChangeSingle(x1 : single; var x2 : single); export;   
                                        {Note export directive}
  implementation
  procedure ChangeInt(x1 : integer; var x2 : integer);
  begin
      x2 := x1 * 20;
  end;
  procedure ChangeSingle(x1 : single;  var x2 : single);
  begin
      x2 := x1 * 20.56;
  end;
  end.

This is the code on the test form that contains 2 buttons:

  procedure TForm1.Button1Click (Sender: TObject);
  var
      x1,x2:integer;
  begin
  x1:=4;
  ChangeInt(x1,x2);
  showmessage(inttostr(x2));
  end;
  procedure TForm1.Button2Click (Sender: TObject);
  var
      x1,x2:single;
      s:string ;
  begin
  x1:=4.6;
  Changesingle(x1,x2);
  str(x2:0:3,s);
  showmessage(s);
  end;
  end.

To test the application compile and run in the normal way. To create the DLL project use the rgdll.dpr shown above and compile the project. You cannot Run a DLL project.

Now let’s create the VB end. You will need to create a form with 2 buttons and a module file. In the module put the following declarations:

  Declare Sub changesingle Lib "rgdll.dll" (ByVal x1 As Single, x2 As Single)
  Declare Sub changeint Lib "rgdll.dll" (ByVal x1 As Integer, x2 As Integer)

The following things should be noted:

In the form put the following:

  Sub Command1_Click ()
      Dim x1 As Integer
      Dim x2 As Integer
      x1 = 4
      Call changeint(x1, x2)
      Print x2
  End Sub
  Sub Command2_Click ()
      Dim x1 As Single
      Dim x2 As Single
      x1 = 4.6
      Call changesingle(x1,x2)
      Print x2
  End Sub

If all goes according to plan, you have just created your first DLL.


Image of arrow to previous article Image of arrow to next article

Image of line
[HOME] [TABLE OF CONTENTS] [SEARCH]