Search code examples
delphistaticrecordrttigetvalue

Delphi: How to get the address of a static record


    type
      TMyRecord = record
      private
        class constructor create;
      public
        class var MyField1: string;                
        class var MyField2: integer;            
        class var MyField3: extended;             
        class function ToString: string; static;
      end;

    class constructor TMyRecord.Create;
    begin
        TMyRecord.MyField1 := 'Hello, world!';
        TMyRecord.MyField2 := 123;
        TMyRecord.MyField3 := 3.1415927;
    end;  

    class function TMyRecord.ToString: string;
    var
      RecType: TRTTIType;
      RecFields: TArray<TRttiField>;
      I: integer;
    begin
      RecType := TRTTIContext.Create.GetType(TypeInfo(TMyRecord));
      Result := RecType.ToString;
      RecFields := RecType.GetFields;
      for I := 0 to High(RecFields) do
        Result := Result + Format('%s: %s = %s', [RecFields[I].Name, RecFields[I].FieldType.ToString, RecFields[I].GetValue(@TMyRecord).ToString]) + sLineBreak;
    end;

I am trying to get TMyRecord.ToString to return:

    TMyRecord
    MyField1: string = Hello, world!
    MyField2: integer = 123;
    MyField3: extended = 3.1415927;

However, I get a compiler error on GetValue(@TMyRecord) - E2029 '(' expected but ')' found

Normally GetValue should be called with the address of the 'instance' of the record. But in this case the record is static. I do not want to convert this record to a normal record, create an instance etc. I'm trying to solve this for a static record. How can I get the address that should be passed to GetValue?


Solution

  • To the best of my knowledge, class fields are not accessible through RTTI.