Sign in Join
Wiki copytemporary

Revision 1 of 1, by Trev on 2-13-2020. The page as it is now.

DLL dynamically load

The tutorial shows how a DLL (Dynamic Link Library) is loaded dynamically .

The DLL (DLLTest.dll) referred to in the example below:

pascal
 library info;

 {$mode objfpc} {$H+}

 uses
   SysUtils;

 {$R *.res}

 // The DLL subroutine
 function funStringBack(strIn : string) : PChar;
   begin
     funStringBack := PChar(UpperCase(strIn));
   end ;

 // Exported subroutine(s)
 exports
   funStringBack;

 begin
 end.

What should I do:

Integrate, use and release the DLL subroutine in your own program:

pascal
 uses
   Windows, ...;

   ...

 Include function funDll : string;
 type
   // Definition of the subroutine to be called, as defined in the DLL to be used
   TfunStringBack = function(strIn : string) : PChar;  stdcall;

 var
   // Creates a suitable variable (data field) for the DLL subroutine
   funStringBack : TfunStringBack;
   // Creates a handle for the DLL
   LibHandle : THandle;

 begin
   // Get the handle of the library to be used
   LibHandle := LoadLibrary(PChar('DLLTest.dll'));

   // Checks whether loading the DLL was successful
   if LibHandle <> 0 then
     begin
       // Assigns the address of the subroutine call to the variable funStringBack
       // 'funStringBack' from the DLL DLLTest.dll
       Pointer(funStringBack) := GetProcAddress(LibHandle, 'funStringBack');

       // Checks whether a valid address has been returned
       if @funStringBack <> nil then
         Result := funStringBack('hello world');
     end;

   // release memory
   funStringBack := nil;
   FreeLibrary(LibHandle);

 end;

   ...

From the Free Pascal wiki, page "DLL dynamically load", as it stood on 2020-02-13 after a change by Trev, out of the wiki's dump of 2024-05-26. Copyright stays with the author who wrote it, according to the old wiki's Licensing page. If you have concerns about this material, message the admin.