Sunday, May 3, 2015

Delphi Dynamic method

Marking method in a class as dynamic will place it into special Dynamic Method Table (DMT).

Table contains list of methods, each one has the ID (int16)

User allowed range for ID is: 1 .. $BFFF.

BTW when you use message keyword, this method becomes dynamic. And message id becomes dynamic method id.

DMT can be found at Self + vmtDynamicTable constant.

At DMT first there comes uint16 Count (number of dynamic methods).

Then comes two arrays/lists:

  • array [Count] of INT16 (IDs)
  • array [Count] of POINTER, i.e either uint32 or uint64 (Pointers to code of method)
To find dynamic method there's following function in System unit:

function GetDynaMethod(vmt: TClass; selector: SmallInt): Pointer;

Selector is ID.

It tries to find method by ID in DMT of this class or all the parents.

It goes through first array to find Selector ID. If it's found we know index in first array and we take method address from second table by this index.

If there is a lot of dynamic methods which are called often it can make things some slower. But usually there's no real need to use dynamic methods except messages.

I think DMT could be optimized using binary search instead of linear scan.

No comments:

Post a Comment