[fpc-pascal] Dynamically Execute method

Ludo Brands ludo.brands at free.fr
Tue Jun 19 09:28:07 CEST 2012

> Seems to work for me, updated the example: https://gist.github.com/2950789
> Or am O missing something ?

Change your method to 

procedure TMyClass.SayHi;
  writeln('Hi World from '+IntToStr(ptruint(self)));

And the test to

 write('From MyClass2 : ');
 if not ExecMethod(MyClass2, 'SayHi') then
   writeln(STDERR, 'Could not find SayHi method on MyClass2 instance');

And you'll get something like:

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

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.


More information about the fpc-pascal mailing list