Introduction to DLLs. How to create (and use) a DLL in Delphi
A Dynamic Link library, or DLL, is a collection of routines (small programs) that can be called by applications and by other DLLs. Like units, DLLs contain sharable code or resources, they provide the ability for multiple applications to share a single copy of a routine they have in common. The concept of DLLs is the core of the Windows architectural design, and for the most part Windows is simply a collection of DLLs.
Creating a Dynamic Link LibraryThe following few lines will demonstrate how to create a simple DLL using Delphi.
For the beginning start Delphi and select File | New ... DLL. This will create a new DLL template in the editor window. Select the default text and replace it with the next piece of code.
uses SysUtils, Classes, Dialogs;
procedure DllMessage; export;
___begin ShowMessage('Hello world from a Delphi DLL') ;
If you look at the project file of any Delphi application, you’ll see that it starts with the reserved word Program. By contrast, DLLs always begin with the reserved word Library. This is then followed by a uses clause for any needed units. In this simple example, there then follows a procedure called DllMessage which does nothing except showing a simple message.
At the end of the source code we find an exports statement. This lists the routines that are actually exported from the DLL in a way that they can be called by another application. What this means is that we can have, let's say, 5 procedures in a DLL and only 2 of them (listed in the exports section) can be called from an external program (the remaining 3 are "sub procedures" in a DLL).
In order to use this simple DLL, we have to compile it by pressing Ctrl+F9. This should create a DLL called SimpleMessageDLL.DLL in your projects folder.
Finally, let's see how to call the DllMessage procedure from a (statically loaded) DLL.
To import a procedure contained in a DLL, we use the keyword external in the procedure declaration. For example, given the DllMessage procedure shown earlier, the declaration in the calling application would look like :
procedure DllMessage; external 'SimpleMessageDLL.dll'
the actual call to a procedure will be nothing more than
DllMessage;The entire code for a Delphi form (name: Form1) with a TButton on it (name: Button1) that's calls the DLLMessage function could be:
unit Unit1;That all! As simple as only Delphi can be.
For more info on creating and using Dynamic Link Libraries from Delphi: Everything you ever wanted to know about DLLs and Delphi but didn't know where to look for answers (or were to afraid to ask). Papers, tutorials, articles, code, what, how, why, when, where...