Skip to content

Instantly share code, notes, and snippets.

@ik5
Created June 18, 2012 21:17
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ik5/2950789 to your computer and use it in GitHub Desktop.
Save ik5/2950789 to your computer and use it in GitHub Desktop.
How dynamically execute a method in Object Pascal Class
{$mode objfpc}{$M+}
program test;
type
TMyClass = class
procedure SayHi;
end;
procedure TMyClass.SayHi;
begin
writeln('Hi World ', ptruint(self));
end;
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(Exec);
if Result then Exec;
end;
var
MyClass, MyClass2 : TMyClass;
begin
MyClass := TMyClass.Create;
MyClass2 := TMyClass.Create;
write('From MyClass : ');
if not ExecMethod(MyClass, 'sayhi') then
writeln(STDERR, 'Could not find SayHi method on MyClass instance');
MyClass.Free;
write('From MyClass2 : ');
if not ExecMethod(MyClass2, 'sayhello') then
writeln(STDERR, 'Could not find SayHello method on MyClass2 instance');
write('From MyClass2 : ');
if not ExecMethod(MyClass2, 'SayHi') then
writeln(STDERR, 'Could not find SayHi method on MyClass2 instance');
MyClass2.free;
end.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment