Friday, 15 February 2013

Delphi object references

I was wondering whether a selection of objects in a program were in fact the same object as they were supposed to be.
As far as I understand an object points to the actual instance of the object, i.e. the value of an object is a reference to the memory where the actual object is.
A simple console app to clarify this is below, giving the results

Object1     >7036359053610256
Object1 loc >4341464
Object2    >7036359021690880
Object2 loc>4341468
set Object2 to Object1
Object2    >7036359053610256
Object2 loc>4341468

Object1 and Object2 have two different addresses. 4341464 and 4341468
However on setting object1 to object2 the contents at those memory addresses is the same
7036359053610256 which points to the exact same instance of an object.





program testObjRef;

{$APPTYPE CONSOLE}

{$R *.res}

uses
  System.SysUtils,windows;
var
object1 : TObject;
object2 : TObject;


  function GetObjectReference(thisObject : TObject) : string;
  var
  p: Pointer;
  begin
    p := @thisObject;
    Result := intToStr(uint64(p^));
  end;


begin
  try
    { TODO -oUser -cConsole Main : Insert code here }
  object1 := TObject.Create;
  writeln('Object1     >' + GetObjectReference(object1));
  writeln('Object1 loc >' + IntToStr(uint64(@object1)));
  writeln('Object2    >' + GetObjectReference(object2));
  writeln('Object2 loc>' + IntToStr(uint64(@object2)));
  writeln('set Object2 to Object1');
  object2 := object1;
  writeln('Object2    >' + GetObjectReference(object2));
  writeln('Object2 loc>' + IntToStr(uint64(@object2)));



  except
    on E: Exception do
      Writeln(E.ClassName, ': ', E.Message);
  end;
end.

No comments:

Post a Comment