DLL dynamically load/zh CN

From Lazarus wiki
Revision as of 02:12, 19 October 2021 by Robsean (talk | contribs) (Created page with "{{DLL_dynamically_load |DLL_动态地_加载}} 这篇教程向你展示如何动态地加载一个DLL(动态链接库)。 The DLL (DLLTest.dll) referred to in the example be...")
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to navigationJump to search
Windows logo - 2012.svg

This article applies to Windows only.

See also: Multiplatform Programming Guide

Deutsch (de) English (en) русский (ru) 中文(中国大陆)‎ (zh_CN)


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

 library info;

 {$mode objfpc} {$H+}


 {$R *.res}

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

 // Exported subroutine(s)



  • 定义存储器
    • A data type must be created that corresponds exactly to the (external) subroutine that is to be imported from the DLL.
  • 保留存储器
    • Memory must be reserved for a variable (data field) to which the above data type is assigned.
    • Memory must be reserved for a handle, to which the DLL handle will be assigned later.
  • Assign DLL and external subroutine and accept the data
    • Call the DLL and assign the handle of the DLL to the handle.
    • The pointer for the variables must be changed to the memory of the external subroutine.
    • The result of the external subroutine is to be accepted.
  • Free all memory
    • The pointer for the variables must point to an invalid memory area again (:= nil) to release the external subroutine.
    • The memory of the DLL must be released again.

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

   Windows, ...;


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

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

   // 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
       // 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');

   // release memory
   funStringBack := nil;