使用 Delphi XE。
当尝试从 DLL 访问 Delphi 接口(interface)对象时,如果我尝试动态而不是静态地进行访问,则会失败。
dll中的接口(interface)单元实现了一个返回接口(interface)实例的函数。当静态链接时,输入函数时结果为 nil,一切正常。动态加载时,结果不是 nil,因此当对结果赋值时,IntFCopy 代码将其视为非 nil,因此尝试在赋值之前释放它,这会引发异常。
如有任何见解,我们将不胜感激。
DLL 包含 testinterfaceload_u 并导出 testInt:
library testinterfaceload;
uses
SimpleShareMem,
SysUtils,
Classes,
testinterfaceload_u in 'testinterfaceload_u.pas';
{$R *.res}
exports testInt;
begin
end.
testinterfaceload_u是定义接口(interface)和简单类实现的单元:
unit testinterfaceload_u;
interface
type ITestInt = interface
procedure Test;
end;
{this function returns an instance of the interface}
function testInt : ITestInt; stdcall; export;
type
TTestInt = class(TInterfacedObject,ITestInt)
procedure Test;
end;
implementation
function testInt : ITestInt;
begin
//debugger shows result as non-nil ITestInt even before this assignment, when dynamic
result := TTestInt.Create;
end;
procedure TTestInt.Test;
var
i : integer;
begin
i := 0;
end;
end.
这是一个控制台应用程序,它加载 dll 并调用 testInt 函数返回接口(interface):
program testload_console;
{$APPTYPE CONSOLE}
uses
SysUtils,
Windows,
testinterfaceload_u in 'testinterfaceload_u.pas';
type
TTestInt = function() : ITestInt;
var
TestInt: TTestInt;
NewTestInt : ITestInt;
DLLHandle: THandle;
begin
DLLHandle := LoadLibrary('testinterfaceload.dll');
if (DLLHandle < HINSTANCE_ERROR) then
raise Exception.Create('testinterfaceload.dll can not be loaded or not found. ' + SysErrorMessage(GetLastError));
@TestInt := GetProcAddress(DLLHandle, 'testInt');
try
if Assigned(TestInt) then
NewTestInt := TestInt;
except on e:Exception do
WriteLn(Output,e.Message);
end;
end.
最佳答案
TTestInt
需要在导入DLL的代码中声明为stdcall
。
关于来自 DLL 的 Delphi 接口(interface),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6629852/