来自 DLL 的 Delphi 接口(interface)

标签 delphi dll interface loadlibrary

使用 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/

相关文章:

go - 通过注入(inject)类型查找 slice 元素的模式

c# - c#8 中的公共(public)接口(interface)成员

delphi - ANTLR4 的 Delphi 语法问题

c++ - 捕获从 DLL 抛出的异常

c++ - Worker/Controller 多线程和接口(interface)类

c++ - 在 C++ 中构建和使用 DLL 时遇到问题

c++ - Visual C++ 中 DLL 的 DLL 导出和接口(interface)

delphi - 奇怪的 THotkey 行为 - 它不允许连续使用相同的热键

delphi - 如何使用 RTTI 设置嵌套属性的值

delphi - 如何在 Delphi 2010 中禁用格式化程序