Delphi中动态调用dll的方法如下:
- function CallFunc(dllname, funcname: string; const param: array of const): DWORD;
- var
- hLib: THandle;
- pFunc: Pointer;
- intSize: Integer;
- begin
- Result := 0;
- hLib := LoadLibrary(PChar(dllname));
- if hLib <> 0 then begin
- pFunc := GetProcAddress(hLib, PChar(funcname));
- if pFunc <> nil then begin // 获取参数大小 intSize := Length(param);
- // 以下汇编码将自动完成函数调用 asm
- push ecx
- push esi
- mov ecx, intSize; // 参数的个数 mov esi, param
- test ecx, ecx // 判断是否有参数 je @call // 如果没有参数则跳转到函数调用处
- @again:
- dec ecx
- push dword ptr [esi + ecx * 8] // 循环把参数压入堆栈 cmp ecx, 0
- jnz @again // 一直循环到 ecx 为0
- @call:
- call pFunc // 调用函数 mov @Result, eax // 返回值
- pop esi
- pop ecx
- end;
- end;
- FreeLibrary(hLib);
- end;
- end;
然后调用的时候如下:
- CallFunc('user32.dll', 'MessageBoxA', [0, 'hello world', 'title', MB_OK]);
- CallFunc('user32.dll', 'MessageBeep', []);
- CallFunc('kernel32.dll', 'Sleep', [1000]);
Delphi动态调用DLL
本文介绍了一种在Delphi中动态调用DLL文件的方法,包括加载DLL、获取函数地址及通过汇编指令调用函数的过程。展示了如何传递参数并处理返回值。

3568





