Delphi中动态调用DLL的方法

Delphi动态调用DLL
本文介绍了一种在Delphi中动态调用DLL文件的方法,包括加载DLL、获取函数地址及通过汇编指令调用函数的过程。展示了如何传递参数并处理返回值。

Delphi中动态调用dll的方法如下:

[delphi]  view plain  copy
 print ? 在CODE上查看代码片 派生到我的代码片
  1. function CallFunc(dllname, funcname: stringconst param: array of const): DWORD;  
  2. var  
  3.    hLib: THandle;  
  4.    pFunc: Pointer;  
  5.    intSize: Integer;  
  6. begin  
  7.    Result := 0;  
  8.   
  9.    hLib := LoadLibrary(PChar(dllname));  
  10.    if hLib <> 0 then begin  
  11.      pFunc := GetProcAddress(hLib, PChar(funcname));  
  12.      if pFunc <> nil then begin // 获取参数大小 intSize := Length(param);  
  13.   
  14.        // 以下汇编码将自动完成函数调用 asm  
  15.          push ecx  
  16.          push esi  
  17.   
  18.          mov ecx, intSize;   // 参数的个数          mov esi, param  
  19.   
  20.          test ecx, ecx       // 判断是否有参数 je @call // 如果没有参数则跳转到函数调用处  
  21.        @again:  
  22.          dec ecx               
  23.          push dword ptr [esi + ecx * 8// 循环把参数压入堆栈 cmp ecx, 0            
  24.          jnz @again           // 一直循环到 ecx 为0  
  25.        @call:  
  26.          call pFunc           // 调用函数 mov @Result, eax // 返回值  
  27.          pop esi  
  28.          pop ecx  
  29.        end;  
  30.      end;  
  31.   
  32.      FreeLibrary(hLib);  
  33.    end;  
  34. end;  

然后调用的时候如下:

[delphi]  view plain  copy
 print ? 在CODE上查看代码片 派生到我的代码片
  1. CallFunc('user32.dll''MessageBoxA', [0'hello world''title', MB_OK]);  
  2. CallFunc('user32.dll''MessageBeep', []);  
  3. CallFunc('kernel32.dll''Sleep', [1000]);  
评论 1
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值