In Delphi, you can load a DLL dynamically at runtime using the LoadLibrary
function from the Windows API. Here’s a simple example demonstrating how to load a DLL dynamically and call a function:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 |
unit MainUnit; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs; type TForm1 = class(TForm) procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); private DLLHandle: HMODULE; AddNumbersFunc: function(a, b: Integer): Integer; stdcall; public { Public declarations } end; var Form1: TForm1; implementation {$R *.dfm} procedure TForm1.FormCreate(Sender: TObject); begin // Load the DLL dynamically DLLHandle := LoadLibrary(‘MyDLL.dll’); if DLLHandle <> 0 then begin // Get the address of the exported function @AddNumbersFunc := GetProcAddress(DLLHandle, ‘AddNumbers’); if @AddNumbersFunc <> nil then begin // Call the function ShowMessage(‘Result: ‘ + IntToStr(AddNumbersFunc(5, 7))); end else ShowMessage(‘Function not found in DLL.’); end else ShowMessage(‘DLL not loaded.’); end; procedure TForm1.FormDestroy(Sender: TObject); begin // Unload the DLL if DLLHandle <> 0 then FreeLibrary(DLLHandle); end; end. |
In this example:
- The
LoadLibrary
function is used to load the DLL dynamically. This function returns a handle to the loaded module (DLLHandle
). - The
GetProcAddress
function is used to obtain the address of the exported function (AddNumbers
in this case). If the function is found, its address is assigned to theAddNumbersFunc
variable. - The
AddNumbersFunc
variable, when notnil
, can be used like a regular Delphi function. - Finally, the
FreeLibrary
function is called to unload the DLL when it’s no longer needed.
Make sure to handle potential errors, such as when the DLL cannot be loaded or when the function is not found, to ensure robustness in your application. Additionally, consider using exception handling to manage errors in a more controlled manner.
Leave a Reply