Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get Variable Name Using RTTI

Tags:

delphi

rtti

I'm trying to get variable name using RTTI like this.

Here is my test.

type
  TStringHelper = record helper for string
    function Name: string;
  end;

  TMyRecord = record
    Field1:string;
  end;

implementation

{ TStringHelper }
function TStringHelper.Name: string;
var
 context : TRttiContext;
begin
 context := TRttiContext.Create;
 result := context.GetType(@Self).Name; // return empty
 context.Free;
end;

procedure TForm2.FormCreate(Sender: TObject);
var
 r : TMyRecord;
begin
  ShowMessage(r.Field1.Name);
end;

Name of TRttiType returning is empty.

Is there any way get variable name ?

like image 320
İsmail Kocacan Avatar asked Nov 02 '16 06:11

İsmail Kocacan


1 Answers

RTTI gives information about types and not about variables. In general there is no way, using RTTI, given the address of a variable, to find its name.

Not only does RTTI not help, but what you are attempting, as a method of a string object, is not actually possible. Imagine a scenario where you have two variables referring to the same object.

S := 'foo';
T := S;

What is the name of the single string object here. Is it S or is it T?

like image 127
David Heffernan Avatar answered Nov 05 '22 14:11

David Heffernan