Search code examples
delphicss-selectorsfieldrecords

dynamic record access


i'm relativity new to delphi and trying to write a complex search algorithm for my a2 computing coursework. i need to access my record field from a string variable. e.g.

         getfield(record,'name');

I have found an article that may solve my problem but i cant make sense of it. please can someone shorten it down to just what i need. Thanks.

http://theroadtodelphi.wordpress.com/2010/10/10/fun-with-delphi-rtti-dump-a-trttitype-definition/


Solution

  • A dead simple adaptation of LU RD's code from their comment. This compiles and works under Delphi XE2, but earlier versions should be fine, too.

    program Project4;
    
    {$APPTYPE CONSOLE}
    
    {$R *.res}
    
    uses
      System.SysUtils, RTTI, TypInfo;
    
    type
      TSampleRecord = record
        SomeInt: Integer;
        SomeStr: String;
        SomeFloat: Single;
      end;
    
    function GetField(Rec: TValue; const FieldName: String): String;
    var
      Context: TRTTIContext;
      RTTIRecord: TRTTIRecordType;
      RecField: TRTTIField;
      RecValue: TValue;
    begin
      if (Rec.Kind = tkRecord) then
      begin
        RTTIRecord := Context.GetType(Rec.TypeInfo).AsRecord;
        RecField := RTTIRecord.GetField(FieldName);
    
        RecValue := RecField.GetValue(Rec.GetReferenceToRawData);
        Result := RecValue.ToString();
    
        if (RecValue.Kind = tkFloat) then
          Result := Format('%.4f', [RecValue.AsExtended]);
      end;
    end;
    
    var
      SR: TSampleRecord;
    begin
      SR.SomeInt := 1992;
      SR.SomeStr := 'Lorem ipsum dolor sit amet';
      SR.SomeFloat := 3.1415;
    
      Writeln(GetField(TValue.From(SR), 'SomeInt'));
      Writeln(GetField(TValue.From(SR), 'SomeStr'));
      Writeln(GetField(TValue.From(SR), 'SomeFloat'));
    
      Readln;
    end.