[fpc-pascal] Read Field names from VMT

Amir at Aavani.net Amir at Aavani.net
Tue Jan 23 07:09:29 CET 2024


   Params := TParams.Create;
   WriteLn(Params.Int2.IntVal);
   WriteLn(TInteger(Params.FieldAddress('Int2')).IntVal);

The third line does not work (the zipped code is attached).

On 1/21/24 23:43, Michael Van Canneyt via fpc-pascal wrote:
>
>
> 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
>>
>
> _______________________________________________
> fpc-pascal maillist  -  fpc-pascal at lists.freepascal.org
> https://lists.freepascal.org/cgi-bin/mailman/listinfo/fpc-pascal
-------------- next part --------------
A non-text attachment was scrubbed...
Name: FieldAddress.lpr.gz
Type: application/gzip
Size: 591 bytes
Desc: not available
URL: <http://lists.freepascal.org/pipermail/fpc-pascal/attachments/20240122/8842a48f/attachment.gz>


More information about the fpc-pascal mailing list