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]);