Jump to content
Davide Visconti

RttiMethod Invoke (invalid class typecast)

Recommended Posts

type
  TMyClass = class
  public
    procedure Run;
  end;

  TMyTool = class
  public
    MyClass: TMyClass;
    constructor Create;
  end;

...
var
  MyTool: TMyTool;

procedure TFrmMain.FormCreate(Sender: TObject);
begin
  MyTool := TMyTool.Create;
end;
procedure TFrmMain.Btn1Click(Sender: TObject);
var
  LCtx             : TRttiContext;
  LType1           : TRttiType;
  LField1          : TRttiField;
  LNestedType1     : TRttiType;
  LRttiInstanceType: TRttiInstanceType;
  LMeth            : TRttiMethod;
begin
  LCtx         := TRttiContext.Create;
  LType1       := LCtx.GetType(MyTool.ClassType);
  LField1      := LType1.GetField('MyClass');
  LNestedType1 := LCtx.GetType(LField1.FieldType.Handle);
  LMeth        := LNestedType1.GetMethod('Run');
  // LMeth.Invoke(MyTool.MyClass, []);  		// <-- ok
  LMeth.Invoke(LNestedType1.AsInstance, []);	// <-- fail
end;

 

I get "invalid class typecast" I understand where is the problem but I don't know how to resolve it.

I have to call the method "MyClass.Run" through RTTI.

Can you help me please?

Any suggestion will be appreciated.

Thank you.

 

 

Share this post


Link to post

This work.

Do you have any suggestions?

procedure TFrmMain.Btn1Click(Sender: TObject);
var
  LCtx             : TRttiContext;
  LType1           : TRttiType;
  LField1          : TRttiField;
  LNestedType1     : TRttiType;
  LRttiInstanceType: TRttiInstanceType;
  LMeth            : TRttiMethod;
  LObj             : TObject;
begin
  LCtx         := TRttiContext.Create;
  LType1       := LCtx.GetType(MyTool.ClassType);
  LField1      := LType1.GetField('MyClass');
  LObj         := LField1.GetValue(MyTool).AsObject;
  LNestedType1 := LCtx.GetType(LField1.FieldType.Handle);
  LMeth        := LNestedType1.GetMethod('Run');
  // LMeth.Invoke(MyTool.MyClass, []); // ok
  // LMeth.Invoke(LNestedType1.AsInstance.ClassInfo, []); // fail
  LMeth.Invoke(LObj, []);
end;

 

Share this post


Link to post

procedure Run is a method of object, not a class method. So you need an object instance to call the method.

Share this post


Link to post

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×