Recent

Author Topic: How to invoke an arbitrary method using RTTI?  (Read 211 times)

cpicanco

  • Hero Member
  • *****
  • Posts: 655
  • Behavioral Scientist and Programmer
    • Portfolio
How to invoke an arbitrary method using RTTI?
« on: September 01, 2024, 04:53:19 pm »
Does Free Pascal ({$mode objfpc}) supports invoking arbitrary methods with RTTI?

Did Michael wrote a continuation of this documentation: https://www.freepascal.org/~michael/articles/rtti1/rtti1.pdf? He mentioned that invoking arbritrary methods would be explored in next chapters.

This Chat GPT answer did not worked:
Code: Pascal  [Select][+][-]
  1. uses
  2.   sysutils, rtti;
  3.  
  4. type
  5.   TMyClass = class
  6.     procedure MyMethod;
  7.   end;
  8.  
  9. procedure TMyClass.MyMethod;
  10. begin
  11.   writeln('MyMethod has been called');
  12. end;
  13.  
  14. var
  15.   ctx: TRttiContext;
  16.   typ: TRttiType;
  17.   method: TRttiMethod;
  18.   instance: TObject;
  19. begin
  20.   instance := TMyClass.Create;
  21.   try
  22.     ctx := TRttiContext.Create;
  23.     try
  24.       typ := ctx.GetType(TMyClass);
  25.       method := typ.GetMethod('MyMethod');
  26.       if Assigned(method) then
  27.         method.Invoke(instance, []);
  28.     finally
  29.       ctx.Free;
  30.     end;
  31.   finally
  32.     instance.Free;
  33.   end;
  34. end.

PS.: There is a recent question in StackOverflow on how to use the invoke method: https://stackoverflow.com/questions/78922855/in-lazarus-fpc-how-do-i-get-a-pointer-to-a-class-or-record-method/78927526?noredirect=1#comment139161075_78927526)
Be mindful and excellent with each other.
https://github.com/cpicanco/

 

TinyPortal © 2005-2018