Dumping field names and offset

Given there's a single type declaration,

THDItem

and that I wanted to see the field offsets as well as calculate the total size of the record, using Delphi's RTTI, I can do so with:

var

  rtype: TRTTIType;
  fields: TArray<TRTTIField>;
  LFieldName: string;
  P: Pointer;
  LTotalSize: Integer;
  LHDItem: THDItem;

begin

  rtype := TRTTIContext.Create.GetType(TypeInfo(THDItem));
  P := @LHDItem;

  fields := rtype.GetFields;
  for i := 0 to High(fields) do
    begin
      LFieldName := fields[i].Name;
      if LFieldName.StartsWith('placeholder', True) then
        Continue;
      WriteLn(Format('%-20s: %-10s :: %-30s, Addr: %.8x', [
        LFieldName,
        fields[i].FieldType.ToString,
        fields[i].GetValue(P).ToString,
        fields[i].Offset]));
      LTotalSize := LTotalSize + fields[i].FieldType.TypeSize;
    end;
  WriteLn('Size: ', LTotalSize);

end;
Published Sun, 27 Jan 2019 @ 9:59 PM by chuacw
Related articles: ,

Leave a Comment

(required) 
(required) 
(optional)
(required) 
Enter the following code to ensure that your comment reaches the intended party:
Enter the numbers you see in the image: