All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.sonar.l10n.delphi.rules.community-delphi.CharacterToCharacterPointerCast.html Maven / Gradle / Ivy

There is a newer version: 1.12.1
Show newest version

Why is this an issue?

Casting a Character type (e.g. Char, AnsiChar) to a Character Pointer type (PChar, PAnsiChar) is non-portable between different versions of Delphi.

Before Delphi 10.4, casting a character type to a character pointer type would take the ordinal value of the character and convert it to a pointer.

In Delphi 10.4 and above, a new single-character string is constructed and the pointer to that string is returned instead.

Because its behaviour is not consistent between Delphi versions, to maintain compatibility it should not be used.

How to fix it

To consistently use the pre-Delphi 10.4 behaviour, convert the character to its ordinal value before casting.

procedure Example(MyChar: Char);
var
  MyPointer: PChar;
begin
  MyPointer := PChar(MyChar);
end;
procedure Example(MyChar: Char);
var
  MyPointer: PChar;
begin
  MyPointer := PChar(Ord(MyChar)); // Pointer containing the ordinal value of the character
end;

To consistently use the post-Delphi 10.4 behaviour, cast the character to a string type before casting to the character pointer type:

procedure Example(MyChar: Char);
var
  MyPointer: PChar;
begin
  MyPointer := PChar(MyChar);
end;
procedure Example(MyChar: Char);
var
  MyPointer: PChar;
begin
  MyPointer := PChar(String(MyChar)); // Pointer to a string containing the character
end;

Resources





© 2015 - 2024 Weber Informatics LLC | Privacy Policy