2

使用德尔福 XE。

当尝试从 DLL 访问 Delphi 接口对象时,如果我尝试动态地而不是静态地执行它会失败。

dll中的接口单元实现了返回接口实例的函数。静态链接时,输入函数时结果为零,一切正常。动态加载时,结果为非零,因此当对结果的赋值完成时,IntFCopy 代码将其视为非零,因此尝试在赋值之前释放它,这会引发异常。

任何见解将不胜感激。

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.
4

4 回答 4

5

TTestInt需要stdcall在导入 DLL 的代码中声明。

于 2011-07-08T20:27:11.980 回答
5

您的接口定义应该包含一个 GUID,并且每个函数都需要“stdcall”声明。没有它你可能会遇到问题..

type ITestInt = interface
  ['{AA286610-E3E1-4E6F-B631-F54BC6B31150}']
  procedure Test; stdcall
end;
于 2012-12-04T19:31:00.310 回答
3

试一试:尝试在控制台应用程序中的 dll 的 testInt 函数和 TTestInt 函数类型的声明中添加调用方法(stdcall、pascal 等)。

于 2011-07-08T20:25:29.160 回答
1

开启死灵贴模式

function testInt : ITestInt;
begin
//debugger shows result as non-nil ITestInt even before this assignment, when dynamic
  result := TTestInt.Create;  
end;

应该是这样的程序

procedure testInt(out intf: ITestInt); stdcall;
begin
 intf := TTestInt.Create;  
end;
于 2020-10-16T22:33:01.043 回答