Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.