Author: Tomas Rutkauskas
I have a reference to a TMethod (with its Data and Code pointers) and would like to
execute the associated method. Does anyone know how I can do this?
Answer:
Here is an example that executes a method by name. Note that the method to be
called (in the example that is SomeMethod) must be declared as published, otherwise
MethodAddress wil return nil.
1 { ... }2 type3 PYourMethod = ^TYourMethod;
4 TYourMethod = procedure(S: string) ofobject;
5 6 procedure TMainForm.Button1Click(Sender: TObject);
7 begin8 ExecMethodByName('SomeMethod');
9 end;
10 11 procedure TMainForm.ExecMethodByName(AName: string);
12 var13 PAddr: PYourMethod;
14 M: TMethod;
15 begin16 PAddr := MethodAddress(AName);
17 if PAddr <> nilthen18 begin19 M.Code := PAddr;
20 M.Data := Self;
21 TYourMethod(M)('hello');
22 end;
23 end;
24 25 procedure TMainForm.SomeMethod(S: string);
26 begin27 ShowMessage(S);
28 end;