[fpc-pascal] Dynamically Execute method

ik idokan at gmail.com
Tue Jun 19 12:38:47 CEST 2012


On Tue, Jun 19, 2012 at 10:38 AM, Ludo Brands <ludo.brands at free.fr> wrote:

>
> > 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
>

Thank you Ludo, Mattias and Bernd.
It works well now :)


>
> _______________________________________________
> fpc-pascal maillist  -  fpc-pascal at lists.freepascal.org
> http://lists.freepascal.org/mailman/listinfo/fpc-pascal
>


Ido
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.freepascal.org/pipermail/fpc-pascal/attachments/20120619/f52ca427/attachment.html>


More information about the fpc-pascal mailing list