From Social Madrill, 7 Years ago, written in Delphi (Object Pascal).
This paste is a reply to Invokable from Asbjørn
- go back
Embed
Viewing differences between Invokable and Re: Invokable
uses
  System.SysUtils, System.TypInfo, System.Rtti;

type
  IWidget<T> = interface
    procedure SetInstance(const Inst: T);
  end;

  TWidgetImpl<T> = class(TInterfacedObject, IWidget<T>)
  public
    procedure SetInstance(const Inst: T);
  end;

{ TWidgetImpl<T> }

In this method:

-------------------------
procedure TWidgetImpl<T>.SetInstance(const Inst: T);
var
  ctx: TRttiContext;
  typ: TRttiType;
  m: TRttiMethod;
begin
  typ := ctx.GetType(TypeInfo(T));
  m := typ.GetMethod('Initialize');
  if (Assigned(m)) then
  begin
    m.Invoke(TValue.From<T>(Inst), []);
  end;
end;

type
  TObjInst = class
  public
    procedure Initialize;
  end;

{ TObjInst }

procedure TObjInst.Initialize;
begin
  WriteLn('TObjInst.Initialize');
end;

type
  IIntfInst = interface(IInvokable)
    procedure Initialize;
  end;

  TIntfInstImpl = class(TInterfacedObject, IIntfInst)
  public
    procedure Initialize;
  end;

{ TIntfInstImpl }

procedure TIntfInstImpl.Initialize;
begin
  WriteLn('IIntfInst.Initialize');
end;

var
  wo: IWidget<TObjInst>;
  o: TObjInst;
  wi: IWidget<IIntfInst>;
  i: IIntfInst;
begin
  wo 
end;
--------------
I have a private var (fSubscriber) of T and I get access like this:

typ 
:= TWidgetImpl<TObjInst>.Create;
  o := TObjInst.Create;
  wo.SetInstance(o);


  wi := TWidgetImpl<IIntfInst>.Create;
  i := TIntfInstImpl.Create;
  wi.SetInstance(i);

  ReadLn;
end.
ctx.GetType((fSubscriber as TObject).ClassInfo);
....
m.Invoke((fSubscriber as TObject),[]);


Your code is different in these two lines. I think I tried to use TypeInfo and didn't work nicely if I recall correctly. 
Is it wrong what I am doing?

Thanks