Author: Tomas Rutkauskas
What is the correct way to store form method pointers on a TList then use the TList
items[] to call the various procedures?
Answer:
This isn't as easy as it seems. Despite the name, method pointers aren't pointers,
they're 8-byte records (type TMethod, check the Help). So, you have to New a
TMethod on the heap for each method pointer you want to store to the list, and of
course free the records before you clear or free the list:
1 type2 TmyMethod = procedure(s: string) ofobject;
3 TpMyMethod = ^TmyMethod;
4 TpMethPtr = ^Tmethod;
5 6 procedure addMethodPointer(lst: TList; mp: TmyMethod);
7 var8 p: TpMethPtr;
9 begin10 new(p);
11 p^ := Tmethod(mp);
12 lst.add(p);
13 end;
14 15 procedure clearPointers(lst: TList);
16 var17 j: integer;
18 begin19 for j := 0 to lst.count - 1 do20 begin21 dispose(TpMethPtr(lst[j]));
22 end;
23 end;
The fancy casting in addMethodPointer is so you can change the parameter type for
mp without changing anything else.
The call to a given pointer goes this way:
24 25 TpMyMethod(lst[1])^(myString);