Tutorial::Dynamically Loading DLL's



Accessing and using DLL's in Delphi is easy (see Adding forms to a DLL) in this tutorial I would like to expand on that so as we actually control when the DLL is loaded into memory, and are also responsible for removing it from memory when we are finished using it.

Benefits of dynamically loading DLL's

There are various reasons for using DLL's this way, with the main cost being that of additional coding. By dynamically loading a DLL you decide at runtime which DLL to use. This means you can give your program different functionality depending on which DLL's are present (freeware or shareware versions of a program). A use I have found for this in the past is to include each report that is required by a program in a different DLL and then scan a directory (see Implementing Callback Procedures for an example of how to do this) and build up a list of the available reports. This makes adding and modifying reports very easy.

The Actual Code

This tutorial will use the DLL created in Adding forms to a DLL, this DLL exports one function and one procedure which were declared like:

  procedure ShowDllForm;stdcall;
  function ShowDllFormModal:integer;stdcall;

In order to call these from our application we need to declare two new types which correspond to those in the DLL, these are declared like this:

  TShowForm = procedure;
  TShowFormModal = function :integer;

We now need to create an instance of these two types, which we will do in the private part of our main class.

  ShowForm : TShowForm;
  ShowFormModal : TShowFormModal;

At present a call to either of these functions would result in an access violation as they do not actually point to anything. The next step therefore is to load the DLL and make our two functions point to the corresponding ones in the DLL, this is done like so

 DLLHandle := LoadLibrary('Project1dll.dll');
 if DLLHandle <> 0 then
   @ShowForm := GetProcAddress(DLLHandle, 'ShowDllForm');
   @ShowFormModal := GetProcAddress(DLLHandle, 

All we are doing here is loading the dll into memory (LoadLibrary) and then getting the address (GetProcAddress) of the two functions that we wish to call. We can now call ShowForm and ShowFormModal as if they were standard procedures.

Cleaning Up

When we have finished using the DLL we need to remove it from memory, this is done like:


When the DLL is unloaded you must make sure that you never try to call any of the functions contained in it, otherwise you'll be greeted with an access violation.


As can be seen from this example dynamically loading DLL's is easy once you know how. You can download the full source for this application from here. The source is only useful to see how the above example was done and serves no practical purpose.

Web www.Delphi-Central.com
Delphi Central - Delphi Programming Tutorials, Hints and Tips