Creating and using DLLs (Dynamic Link Libraries) in Delphi involves defining functions or procedures in a separate unit or project, compiling it into a DLL, and then using it in another Delphi application. Here’s a step-by-step guide:
Step 1: Create a DLL project
- Open the Delphi IDE.
- Create a new project: File -> New -> Other -> Dynamic Link Library.
Step 2: Define functions or procedures
In your DLL project, define the functions or procedures you want to export. For example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
library MyDLL; uses SysUtils, Classes; {$R *.res} function AddNumbers(a, b: Integer): Integer; stdcall; begin Result := a + b; end; exports AddNumbers; begin end. |
In this example, the AddNumbers
function is defined, and the exports
section specifies which functions or procedures are accessible from outside the DLL.
Step 3: Build the DLL
Build your DLL project: Project -> Build MyDLL.
Step 4: Use the DLL in another Delphi project
- Create a new Delphi project where you want to use the DLL.
- Declare the functions from the DLL in your new project:
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051unit MyMainForm;interfaceusesWindows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,Dialogs;typeTForm1 = class(TForm)procedure FormCreate(Sender: TObject);procedure FormDestroy(Sender: TObject);privateDLLHandle: THandle;AddNumbersFunc: function(a, b: Integer): Integer; stdcall;public{ Public declarations }end;varForm1: TForm1;implementation{$R *.dfm}procedure TForm1.FormCreate(Sender: TObject);beginDLLHandle := LoadLibrary(‘MyDLL.dll’);if DLLHandle <> 0 thenbegin@AddNumbersFunc := GetProcAddress(DLLHandle, ‘AddNumbers’);if @AddNumbersFunc <> nil thenbegin// Use the functionShowMessage(‘Result: ‘ + IntToStr(AddNumbersFunc(5, 7)));endelseShowMessage(‘Function not found in DLL.’);endelseShowMessage(‘DLL not loaded.’);end;procedure TForm1.FormDestroy(Sender: TObject);beginif DLLHandle <> 0 thenFreeLibrary(DLLHandle);end;end.
In this example, theLoadLibrary
function is used to load the DLL, andGetProcAddress
is used to obtain the address of the exported function. TheAddNumbersFunc
variable is then assigned with the function address and can be used like a regular Delphi function.Step 5: Run your application
Run your new Delphi application, and it should use the functions from the DLL.
Remember to handle errors appropriately, check for
nil
afterGetProcAddress
, and free the library usingFreeLibrary
when you’re done.Make sure the DLL is in the same directory as your executable or is located in a directory listed in the system’s PATH environment variable.
Leave a Reply