Virtual Method Table on Free Pascal

363 views Asked by At

What I'm trying to do is to get the list of fields in a class without an instance... for example:

TAClass=class

a_: Integer;
b_: Integer;

constructor (a,b Integer);

end;

I'm not being able to get the fieldTable from the VMT:

ovmt: PVmt;
ftable: PVmtFieldTable;
finfo: PVmtFieldEntry;

ovmt:=PVmt(TAClass);
ftable := ovmt^.vfieldtable
finfo := ftable^.fields[0]

this way I'm not gettig the list of fields

any help is welcome, thanks in advance

1

There are 1 answers

0
Marco van de Voort On

Afaik the field tables in classic delphi and FPC only work for published fields. Published fields must be class fields (value types like integer must go via properties). Newer Delphi's also allow RTTI for non published fields, but that works differently (different untis), and FPC doesn't support that yet.

I hacked together a small demonstration example since the help for typinfo seems to be light on examples. Note the tpersistent derivation.

{$mode delphi}

uses typinfo,classes;
type
  TAClass=class(Tpersistent)
                   a: tstringlist;
                   b: tlist;
                 end;


 var
      ovmt: PVmt;
      FieldTable: PVMTFieldTable;
      PVMTFieldEntry;
           i: longint;

    begin

         ovmt := PVmt(TAClass);
         while ovmt <> nil do
         begin
           FieldTable := PVMTFieldTable(ovmt^.vFieldTable);
           if FieldTable <> nil then
           begin
             FieldInfo := @FieldTable^.Fields[0];
             for i := 0 to FieldTable^.Count - 1 do
             begin
               writeln(fieldinfo^.name);
               FieldInfo := PvmtFieldEntry(PByte(@FieldInfo^.Name) + 1 + Length(FieldInfo^.Name));
             end;
           end;
           { Try again with the parent class type }
           ovmt:=ovmt^.vParent;
         end;

end.