维基副本镜像

这是 pascal.chat 维基的镜像。编辑、历史记录和登录都在那里。

DLL dynamically load/zh CN

Deutsch · English · Русский · 中文(中国)

这篇教程向你展示如何动态地加载一个DLL(动态链接库)。

在下面的示例中将引用的DLL(在DLLTest.dll中的源文件):

pascal
 library info;

 {$mode objfpc} {$H+}

 uses
   SysUtils;

 {$R *.res}

 // DLL文件中的子程序
 function funStringBack(strIn : string) : PChar;
   begin
     funStringBack := PChar(UpperCase(strIn));
   end ;

 // 导出子程序
 exports
   funStringBack;

 begin
 end.

我应该做什么:

在你自己的程序中,集成/融入、使用和释放DLL中的子程序:

pascal
 uses
   Windows, ...;

   ...

 Include function funDll : string;
 type
   // 照着DLL(在源文件中)所使用的定义的方式,定义将要调用的子程序
   TfunStringBack = function(strIn : string) : PChar;  stdcall;

 var
   // 为DLL子程序创建一个合适的变量(数据字段)
   funStringBack : TfunStringBack;
   // 为DLL创建一个处理程序/句柄
   LibHandle : THandle;

 begin
   // 获取将要使用的库的处理程序/句柄
   LibHandle := LoadLibrary(PChar('DLLTest.dll'));

   // 检查是否成功加载DLL文件
   if LibHandle <> 0 then
     begin
       // 分配子程序调用的存储器地址给变量funStringBack
       // 'funStringBack'来自DLL DLLTest.dll
       Pointer(funStringBack) := GetProcAddress(LibHandle, 'funStringBack');

       // 检查是否已经返回一个有限的存储器内存地址
       if @funStringBack <> nil then
         Result := funStringBack('hello world');
     end;

   // 释放存储器内存
   funStringBack := nil;
   FreeLibrary(LibHandle);

 end;

   ...

贡献者和更改


From the Free Pascal wiki, page "DLL dynamically load/zh CN", as it stood on 2021-11-04 after a change by Robsean, 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.

版本1,最后由WikiArchive于修改。