我有一个 C DLL,想从 Delphi XE3 Update 2 调用它。奇怪的是,在我的项目中,动态调用它与静态调用它不同。这是要重现的“最小”代码(我已经更改了 Lib/函数名):
program testProject;
{$APPTYPE CONSOLE}
{$R *.res}
uses
System.SysUtils, System.classes, Windows;
function keylist_open (keylist: PPointer): Integer; external 'libLib';
var
Handle: HINST;
DLLName: PChar = 'libLib.dll';
type
Tkeylist_open = function(keylist: PPointer): Integer; stdcall;
const
keylist_openDynamic: Tkeylist_open = nil;
var
keylist: Pointer;
begin
Handle := LoadLibrary(DLLName);
if Handle = 0 then
Exit;
@keylist_openDynamic := GetProcAddress(Handle, 'keylist_open');
keylist_open(@keylist);
if (keylist = nil) then
Writeln('static: keylist is nil');
keylist_openDynamic(@keylist);
if (keylist = nil) then
Writeln('dynamic: keylist is nil');
end.
输出是
static: keylist is nil
这意味着动态调用函数不同于静态调用。密钥列表确实通过动态调用正确初始化。查看生成的汇编代码,我意识到变量“keylist”已放入 eax 寄存器:
testProject.dpr.34: keylist_open(@keylist);
004D16A2 B804B04D00 mov eax,$004db004
004D16A7 E8ECC6FFFF call keylist_open
然后
testProject.dpr.12: function keylist_open (keylist: PPointer): Integer; external 'libLib';
004CDD98 FF255CC54D00 jmp dword ptr [$004dc55c]
和另一个跳跃
libLib.keylist_open:
5B364508 E903A23D00 jmp $5b73e710
但是然后是dll(我不知道这是哪个函数,某个入口点或keylist例程)
5B73E710 55 push ebp
5B73E711 8BEC mov ebp,esp
5B73E713 81ECDC000000 sub esp,$000000dc
5B73E719 53 push ebx
5B73E71A 56 push esi
5B73E71B 57 push edi
5B73E71C 8DBD24FFFFFF lea edi,[ebp-$000000dc]
5B73E722 B937000000 mov ecx,$00000037
5B73E727 B8CCCCCCCC mov eax,$cccccccc
...
似乎 eax 参数在 eax 中被覆盖。两行之后,动态调用的代码是:
testProject.dpr.37: keylist_openDynamic(@keylist);
004D16CE 6804B04D00 push $004db004
004D16D3 FF15F0564D00 call dword ptr [$004d56f0]
跳到
libLib.keylist_open:
5B364508 E903A23D00 jmp $5b73e710
因此使用相同的代码。但是由于参数现在没有存储在 eax 中,覆盖 eax 并不重要。
打电话给任何人在这里阐明一下,出了什么问题,即我的静态代码出了什么问题,为什么?