Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
221 views
in Technique[技术] by (71.8m points)

delphi - Will TList.Add(Pointer(someInt64Value)) possibly cause value loss?

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

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

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...