使用Delphi XE。
当尝试从DLL中动态访问Delphi接口对象时,如果尝试动态访问而不是静态访问,则会失败。
在dll中的接口单元实现了一个函数来返回接口的实例。当静态链接时,在进入函数时结果为nil,一切正常。当动态加载时,结果为非nil,因此在执行结果赋值时,IntFCopy代码看到它为非nil,因此在赋值之前尝试释放它,这会导致异常。
任何见解都将不胜感激。
该DLL包括testinterfaceload\_u并导出testInt:
当尝试从DLL中动态访问Delphi接口对象时,如果尝试动态访问而不是静态访问,则会失败。
在dll中的接口单元实现了一个函数来返回接口的实例。当静态链接时,在进入函数时结果为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是定义接口和简单类实现的单元:
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 函数以返回接口:
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.
LoadLibrary
返回 0(即NULL
)。此外,不需要使用export
,它只会造成混淆。请将其删除。 - undefined