Get Variable Name Using RTTI
Asked Answered
M

1

9

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 ?

Melisent answered 2/11, 2016 at 6:53 Comment(0)
S
9

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?

Saltatorial answered 2/11, 2016 at 7:6 Comment(2)
Thank you very much for explain. It would have been nice if RTVI(Run Time Variable Information) had. :)Cohin
Nothing "runtime" needed here. The compiler would just need an intrinsic that turns a symbol into a string at compile time. Just like the nameof function in C# 6. - vote for it: quality.embarcadero.com/browse/RSP-13290Flipflop

© 2022 - 2024 — McMap. All rights reserved.