0

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/

Lawrence
  • 35
  • 5
  • 3
    Why don't you try first, and ask a question if you get stuck. – David Heffernan Feb 01 '13 at 09:02
  • I have iv'e been trying for days now and i cant make sense of it im really just diving in the deep end here and i need a solution. – Lawrence Feb 01 '13 at 09:06
  • Since the record field is `yours` you probably need not RTTI to access it at all. RTTI is required to get information about the types unknown at compile time. – kludg Feb 01 '13 at 09:12
  • @Serg, the field name could be unknown at compile time. – LU RD Feb 01 '13 at 09:28
  • 3
    If you study my answer here, I'm sure you can figure it out: [`Convert Record to Serialized Form Data for sending via HTTP`](http://stackoverflow.com/a/11514088/576719). – LU RD Feb 01 '13 at 09:45
  • http://blog.synopse.info/post/2011/03/12/TDynArray-and-Record-compare/load/save-using-fast-RTTI – Arioch 'The Feb 01 '13 at 09:53

1 Answers1

6

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.
Community
  • 1
  • 1
Pateman
  • 2,727
  • 3
  • 28
  • 43
  • I'm glad I was able to help. You can easily expand this to support more complex record fields. :) Just have a look at the reference I've used here and you should be able to figure it out in a flash. – Pateman Feb 02 '13 at 06:12