Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delphi - W1048 Unsafe typecast of 'string' to 'TFormatSettings'

I'm porting an old project to Delphi XE and I receive this warning on the code bellow.

function RemoveThousandSeperator(Text: String) : String;
Var P : Integer;
begin
  if length(Text) > 3 then begin
    p := Pos(FormatSettings.ThousandSeparator,Text);
   while p >0 do begin
      Delete(Text,p,1);
      p := Pos(FormatSettings.ThousandSeparator,Text);
    end;
  end;
  result := Text;
end;

even FormatSettings.ThousandSeparator is of type char.

LE: I am asking if someone can tell me why this warning occurs. The code is old and it will be remade.

LE2 : In order to get this warning all the warnings needs to be set to true in the Delphi Compiler-Hints & Warnings

LE3: If someone needs it - {$WARN UNSAFE_CAST OFF} makes the warning go off.

LE4: a screenshot of the warning for those who believe that the warning is hard to believe

enter image description here

like image 597
RBA Avatar asked Nov 01 '12 09:11

RBA


1 Answers

The origin of the warning is declaration of FormatSettings variable in SysUtils.pas:

var
  // Note: Using the global FormatSettings variable corresponds to using the
  // individual global formatting variables and is not thread-safe.
  FormatSettings: TFormatSettings absolute CurrencyString;

which casts string (CurrencyString) to record (TFormatSettings).

So the problem that generates the warning is in SysUtils.pas, not in the code you posted, though the warning is generated in your code.


Here is a test case (Delphi XE):

program Project1;

{$APPTYPE CONSOLE}
{$WARN UNSAFE_CAST ON}

type
  TTest = record
    FS: string;
  end;

var
  Str: string;
  Test: TTest absolute Str;

begin
  Str:= 'abc';
  Writeln(Test.FS);   //  W1048 Unsafe typecast of 'string' to 'TTest'
end.
like image 155
kludg Avatar answered Sep 23 '22 05:09

kludg