Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

THandleStream.Create with INVALID_HANDLE_VALUE does not compile

The following code used to compile with Delphi 2007:

constructor TMyFile.Create(const _Filename: string);
begin
  inherited Create(Integer(INVALID_HANDLE_VALUE)));
  // ...
end;

In Delphi XE it fails with the error E1012: Constant expression violates subrange bounds.

The reason is the declaration of THandleStream.Create:

Delphi 2007:

constructor THandleStream.Create(AHandle: Integer);

Delphi XE2:

constructor THandleStream.Create(AHandle: THandle);

with

type
  THandle = NativeUInt;

If I change it to

constructor TMyFile.Create(const _Filename: string);
begin
  inherited Create(THandle(INVALID_HANDLE_VALUE)));
  // ...
end;

It compiles in both, Delphi XE2 and Delphi 2007. In Delphi 2007 it causes a warning "W1012: Constant expression violates subrange bounds" and it causes a runtime error when the Delphi 2007 executable is called.

Is there any way I can change the code so it works in both Delphi versions without having to resort to IFDEFS ?

like image 942
dummzeuch Avatar asked Feb 12 '26 00:02

dummzeuch


1 Answers

THandleStream.Create declares its handle parameter as being of type Integer (signed). Delphi XE2 changes this by declaring it as THandle (unsigned). I'm not sure why this change from signed to unsigned was made. Clearly it had to be widened to 64 bit for 64 bit targets but I'm not sure why the change from signed to unsigned needed to be made.

So far as I can tell, there is no way to get around this problem without conditional compilation.

You could contain the damage by declaring a type like this:

type
{$IFDEF XE2_OR_ABOVE}
  THandleCast = THandle;
{$ELSE}
  THandleCast = Integer;
{$ENDIF}

Then at your call sites you would write

inherited Create(THandleCast(INVALID_HANDLE_VALUE)));

Note that the conditional XE2_OR_ABOVE does not exist and you'll have to work out what the condition really should be.

like image 66
David Heffernan Avatar answered Feb 14 '26 15:02

David Heffernan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!