[fpc-pascal] Dynamically Execute method

Ludo Brands ludo.brands at free.fr
Tue Jun 19 09:38:06 CEST 2012


> As Bern said you can't call an object method without passing 
> the reference to the instance. In this case you are lucky 
> because TMyClass.SayHi doesn't use any properties or class 
> vars. Add a property to TMyClass and try to writeln that 
> property and you will see it fails. What you are doing here 
> is calling SayHi as if it where a class method.
> 

Here is the correct way of doing it:

function ExecMethod(Instance : TObject; Name : String) : Boolean;
type
  TProc= procedure of object;
var 
  method : TMethod;
  exec:tproc;
begin
  method.Data := Pointer(Instance);
  method.Code := Instance.MethodAddress(Name);
  Exec:=TProc(Method);
  Result := Assigned(method.Code);
  if Result then Exec;
end;

Output:

>From MyClass : Hi World from 482800
Hi World from 482800
>From MyClass2 : Hi World from 482816
Hi World from 482816

Ludo




More information about the fpc-pascal mailing list