Assign an anonymous method to an interface variable or parameter?

梦想的初衷 提交于 2019-12-01 02:49:31

This is super easy. I will show you two ways.

var
  P: TProc;
  I: IInterface;
begin
  I := IInterface(Pointer(@P)^);
  TakeInterface(I);
end;

Another way is to declare PInterface

type
  PInterface = ^IInterface;
var
  P: TProc;
  I: IInterface;
begin
  I := PInterface(@P)^;
  TakeInterface(I);
end;

To the best of my knowledge you cannot do what you need with casting.

You can, I suppose, use Move to make an assignment:

{$APPTYPE CONSOLE}
type
  TProc = reference to procedure(const s: string);
  IProc = interface
    procedure Invoke(const s: string);
  end;

procedure Proc(const s: string);
begin
  Writeln(s);
end;

var
  P: TProc;
  I: IProc;

begin
  P := Proc;
  Move(P, I, SizeOf(I));
  I._AddRef;//explicitly take a reference since the compiler cannot do so
  I.Invoke('Foo');
end.

I've honestly no idea how robust this is. Will it work on multiple Delphi versions? Is it wise to rely on obscure undocumented implementation details? Only you can determine whether the gains you make outweigh the negatives of relying on implementation details.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!