delphistructurevmt

Where can I find information on the structure of the Delphi VMT?


The System.pas file contains a fair amount of information on hard-coded VMT offsets, but it doesn't seem to actually say much about the structure of the VMT itself. What I'd really like to know is, is there any way to find out the size of a VMT at runtime, or in other words, how many virtual methods exist for a given class?


Solution

  • What about the VMT structure are you wanting to know? You also do know that it is an internal implementation detail that is subject to change (and has changed over time).

    To answer your specific question, here is a simple way to find the number of virtual methods for a given class:

    function GetVirtualMethodCount(AClass: TClass): Integer;
    begin
      Result := (PInteger(Integer(AClass) + vmtClassName)^ - 
        (Integer(AClass) + vmtParent) - SizeOf(Pointer)) div SizeOf(Pointer);
    end;
    

    This works because I happen to know that the string representing the class name is placed immediately following all the virtual method vectors in the VMT.

    I also know that there are 11 virtual methods (for D2009, 9 for D2007 and prior) on all TObjects that are negatively offset from the VMT pointer itself.

    That is the reason for the vmtParent reference.

    Finally, by using a TClass class reference, you can pass any TObject derived class into this function and get the number of virtual methods.