Search code examples
delphirtti

Delphi - get same field pointer with RTTI e Addr


Can I get the same pointer of a Field with RTTI and Addr(Field)?

eg:

TSomeClass

private FSomeField: Integer;

...

1) MyPointer = Addr(FSomeField) >> $12345

2) RTTI pointer from SameField >> $12345


Solution

  • actually all you need is to get RTTI field offset (TRttiField.Offset) and add it to initial object address (instance address).

    type
        TTest = class(TObject)
          private
            FInt : integer;
            FString : string;
            FBool : boolean;
        end;
    
    var t : TTest;
        ctx : TRttiContext;
        f : TRttiField;
    begin
    
        t := TTest.Create();
        try
            writeln(Format('FInt: %p',[@t.FInt]));
            writeln(Format('FString: %p', [addr(t.FString)]));
            writeln(Format('FBool: %p', [@t.FBool]));
    
            writeln('--------------');
            //field address using rtti
            ctx := TRttiContext.Create();
            try
                for f in ctx.GetType(t.ClassType).GetFields() do begin
                    writeln(Format('%s: %8x', [f.Name, NativeInt(t) + f.Offset]));
                end;
            finally
                ctx.Free();
            end;
    
        finally
            t.Free();
        end;
        readln;
    end.