[fpc-pascal] Read Field names from VMT

Michael Van Canneyt michael at freepascal.org
Mon Jan 22 08:43:27 CET 2024



On Sun, 21 Jan 2024, Amir--- via fpc-pascal wrote:

> How can I set the value?
> I tried something like
>
> Test := TTest.Create
>
> Ptr := Pointer(Test);
> TSub(Ptr+8) := TSub.Create;
>
> But it is not working?

Depending on your platform, it can be an alignment issue.

Use

  function TObject.FieldAddress(const name : shortstring) : pointer;

This function is used internally by the streaming system (see
TComponent.SetReference), so it should always work.

Michael.

>> 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
>>
>> _______________________________________________
>> fpc-pascal maillist  -  fpc-pascal at lists.freepascal.org
>> https://lists.freepascal.org/cgi-bin/mailman/listinfo/fpc-pascal
>
> _______________________________________________
> fpc-pascal maillist  -  fpc-pascal at lists.freepascal.org
> https://lists.freepascal.org/cgi-bin/mailman/listinfo/fpc-pascal
>


More information about the fpc-pascal mailing list