【问题标题】:Using / injecting an interface instance implemented in Delphi in dwscript在dwscript中使用/注入Delphi实现的接口实例
【发布时间】:2015-09-13 00:11:50
【问题描述】:

我想以这种方式使用一个接口(实际上是多个接口):

  • 使在 dwscript 脚本中声明接口的单元可用(如果需要)。

  • 在用 Delphi 编写的主机应用程序中创建实现接口的对象。

  • 以某种方式使这些接口可用于 dwscript 脚本。

  • 并在脚本中正常使用它们。

有没有可能这样做?

我试图在一个类中提供返回这些接口的方法,但是当我通过 RTTI 使用这个类时,那些方法没有找到。

【问题讨论】:

  • 据我所知,目前这是不可能的。接口可以在 TdwsUnit 中声明,但实际上在 Delphi 端实现接口是不可能的。另见:dwsUnit: function returning interface
  • 其实是可以的。只是不是人们期望的方式。给我一点时间输入答案...

标签: delphi dwscript


【解决方案1】:

正如我上面所说,声明一个接口并在 Delphi 端使用TdwsUnit 实现它是不可能的。但是,您可以通过其他方式实现您的目标。

我假设你已经在TdwsUnit 中声明了你的接口和你的类。我们称他们为IMyInterfaceTMyClass

type
  IMyInterface = interface
    procedure SetValue(const Value: string);
    function GetValue: string;
    property Value: string read GetValue write SetValue;
    procedure DoSomething;
  end;

type
  TMyClass = class(TObject)
  protected
    procedure SetValue(const Value: string);
    function GetValue: string;
  public
    property Value: string read GetValue write SetValue;
    procedure DoSomething;
  end;

解决方案 1 - 在运行时更改类声明

TdwsUnit.OnAfterInitUnitTable 事件创建一个事件处理程序并将接口添加到类声明中:

procedure TDataModuleMyStuff.dwsUnitMyStuffAfterInitUnitTable(Sender: TObject);
var
  ClassSymbol: TClassSymbol;
  InterfaceSymbol: TInterfaceSymbol;
  MissingMethod: TMethodSymbol;
begin
  // Add IMyInterface to TMyClass
  ClassSymbol := (dwsUnitProgress.Table.FindTypeLocal('TMyClass') as TClassSymbol);
  InterfaceSymbol := (dwsUnitProgress.Table.FindTypeLocal('IMyInterface') as TInterfaceSymbol);
  ClassSymbol.AddInterface(InterfaceSymbol, cvProtected, MissingMethod);
end;

现在您可以通过脚本中的接口访问该类的实例:

var MyStuff: IMyInterface;
MyStuff := TMyObject.Create;
MyStuff.DoSomething;

解决方案 2 - 使用鸭式打字

由于 DWScript 支持duck typing,您实际上不需要声明您的类实现了接口。相反,您只需说明您需要什么接口,然后让编译器确定对象是否可以满足该需求:

var MyStuff: IMyInterface;
MyStuff := TMyObject.Create as IMyInterface;
MyStuff.DoSomething;

【讨论】:

  • 谢谢。它有效,但我发现它相当复杂。目前我们正在研究替代方案,例如 paxCompiler。直接支持接口,支持移动平台。
猜你喜欢
  • 2016-07-25
  • 2013-04-19
  • 1970-01-01
  • 2019-04-09
  • 1970-01-01
  • 1970-01-01
  • 2015-04-06
  • 2021-03-20
相关资源
最近更新 更多