[fpc-pascal] Read Field names from VMT
Sven Barth
pascaldragon at googlemail.com
Wed Dec 27 16:46:37 CET 2023
Am 26.12.2023 um 21:29 schrieb Amir--- via fpc-pascal:
>
> On 12/26/23 01:14, Sven Barth via fpc-pascal wrote:
>> Amir--- via fpc-pascal <fpc-pascal at lists.freepascal.org> schrieb am
>> Di., 26. Dez. 2023, 07:03:
>>
>> Hi,
>>
>> I want to retrieve the name of the fields in a record/class,
>> at run
>> time. It looks like "TVmt.vFieldTable" is what I need. But I
>> cannot find
>> any documentation about how to explore the content of this table. I
>> appreciate any pointer.
>>
>>
>> This only works for published fields and only fields of type class or
>> interface can be published.
> That would work for me. How can I enumerate over those fields?
You can use the PVmtFieldTable and PVmtFieldEntry types from the TypInfo
unit:
=== code begin ===
program tfield;
{$mode objfpc}{$H+}
uses
TypInfo;
type
{$M+}
TSub = class
end;
TTest = class
published
fTest: TSub;
end;
var
vft: PVmtFieldTable;
vfe: PVmtFieldEntry;
i: SizeInt;
begin
vft := PVmtFieldTable(PVMT(TTest)^.vFieldTable);
Writeln(vft^.Count, ' field(s) with ', vft^.ClassTab^.Count, ' type(s)');
for i := 0 to vft^.Count - 1 do begin
vfe := vft^.Field[i];
Writeln(i, ' -> ', vfe^.Name, ' @ ', vfe^.FieldOffset, ' of type ',
vft^.ClassTab^.ClassRef[vfe^.TypeIndex - 1]^.ClassName);
end;
end.
=== code end ===
=== output begin ===
PS C:\fpc\git> .\testoutput\tfield.exe
1 field(s) with 1 type(s)
0 -> fTest @ 8 of type TSub
=== output end ===
Side note: contrary to what I had originally written only classes, but
not interfaces are allowed for published fields and they need to have $M
enabled.
Regards,
Sven
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.freepascal.org/pipermail/fpc-pascal/attachments/20231227/da03b70e/attachment.htm>
More information about the fpc-pascal
mailing list