Created
June 18, 2012 21:17
-
-
Save ik5/2950789 to your computer and use it in GitHub Desktop.
How dynamically execute a method in Object Pascal Class
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{$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