LLs are a great way to simplify code reuse under Windows and are very easy to create using Delphi. By building up large libraries of objects and methods and storing them in DLLs, you will find your total workload reduced when creating new applications. DLLs also allow you to store code logically in compiled files, allowing you to update and change functionality as you see fit without having to redistribute your entire application. By specifying dynamic loading and using names to identify DLL functions, as long as you don't change the function signature, your application will be able to use your DLL.
Writing DLLs in Delphi is straightforward. You need only decide whether your DLL needs to be accessible from only Delphi programs or also from C++ or VB programs before getting started. The differences in accessibility are minor but they are important, so make up your mind first. If your DLL is going to be used by other languages, always use the stdcall calling convention, which Windows uses. If you know that your DLL will be used only by Delphi applications and libraries, then use the register calling convention. The register convention is faster but cannot be used by applications written in other languages. Generally, using stdcall is safer because you don't have to worry about your library in the future.
Build a Simple DLL
To start building your DLL, select File | New from Delphi's main menu. From the dialog, select the DLL project. This will open the code editor with the DLL main project file. Save this file as MyDll.dpr. Most instructional Delphi books will tell you to put your methods and/or structures right in this file and be done with it, but if you're really going to use DLLs, you should separate your files in some logical order. I'll demonstrate how in the following paragraphs.
Select File | New and select Unit from the New Items dialog. Save this file as uDll.pas, this is where you will place your code. For an easy start, let's write a function that passes a string into the DLL and returns a Boolean value. uDll.pas should look as follows:
Listing 1: Simple DLL Unit unit uDLL; interface uses Dialogs;
function DisplayMsg(s:String):Boolean;stdcall;
implementation
function DisplayMsg(s:String):Boolean;stdcall; begin ShowMessage(s); Result := True;end;
end.
Remember to put the uses clause in exactly as shown. If you're missing the Dialogs unit, you'll get a compile time error.
|