Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

With the following Delphi code:

var
  myInt64Value: Int64;
  list: TList;
...
  myInt64Value := High(Int64);
  list.Add(Pointer(myInt64Value));

Question - Will list.Add(Pointer(myInt64Value)) cause value loss when compiling for Win32 platform?

I'm asking this because TList internally uses an array of Pointer to store the values, and on a 32bit platform the length of the Pointer type is 4 bytes while the Int64 type's length is 8 bytes. So will the casting that happens when executing Pointer(myInt64Value) cause value loss if the value of myInt64Value is larger than High(NativeInt) (NativeInt has the same length of Pointer if I understand it correctly)?

Update 1

I coded a testing project and it shows that the answer is YES - will cause value loss. Please correct me if I'm wrong.

Testing code:

program TestInt64ToPointerCastingPrj;
{$APPTYPE CONSOLE}
{$R *.res}

uses
  System.SysUtils,
  System.Classes;

var
  list: TList;
  myInt: NativeInt;
  myInt64: Int64;
begin

  list := TList.Create;
  try

    // Test NativeInt value to Pointer casting
    myInt := High(NativeInt);
    WriteLn('High(NativeInt) : ' + IntToStr(myInt));
    list.Add(Pointer(myInt));
    WriteLn('NativeInt(list[0]) : ' + IntToStr(NativeInt(list[0])));

    // Test Int64 value to Pointer casting
    myInt64 := High(Int64);
    WriteLn('High(Int64) : ' + IntToStr(myInt64));
    list.Add(Pointer(myInt64));
    WriteLn('Int64(list[1]) : ' + IntToStr(Int64(list[1])));

  finally  
    list.Free;
  end;

  ReadLn;

end.

Testing Result:

High(NativeInt) : 2147483647
NativeInt(list[0]) : 2147483647
High(Int64) : 9223372036854775807
Int64(list[1]) : 4294967295
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
204 views
Welcome To Ask or Share your Answers For Others

1 Answer

Yes, this will, in general, lead to loss of data.

As you say, in a 32-bit application, a pointer is 32 bits, so a pointer variable cannot possibly store a general 64-bit integer value. Only if the 64-bit value happens to lie within the 32-bit range will it be preserved; otherwise, you lose data. As you know, High(Int64) is way beyond the 32-bit range.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...