Casting Delphi 2009/2010 string literals to PAnsiChar

前端 未结 4 1476
一向
一向 2021-02-11 01:33

So the question is whether or not string literals (or const strings) in Delphi 2009/2010 can be directly cast as PAnsiChar\'s or do they need an additional cast to AnsiString fi

相关标签:
4条回答
  • 2021-02-11 01:46

    As Mason Wheeler points out all is fine as long as you don't have non-ANSI characters in your string const. If you have things like:

    const FRED = 'Frédérick';
    

    I'm pretty sure Delphi 2009/2010 will either issue charset hints (and apply a string conversion automatically - thus the hint) or fail at comparing ('Frédérick' is different in ISO-8859-1 than UTF-16).

    If you can have "special" characters in your consts you will need to call string conversion.

    Here are some basic examples with TStringList:

    TStringList.SaveToFile(DestFilename, TEncoding.GetEncoding(28591)); //ISO-8859-1 (Latin1)
    TStringList.SaveToFile(DestFilename, TEncoding.UTF8);
    
    0 讨论(0)
  • 2021-02-11 01:47

    To 'visualize' Barry Kelly and Mason Wheeler words:

    const
      FRED = 'Fred';
    
    var
      p: PAnsiChar;
      w: PWideChar;
    begin
      w := PWideChar(Fred);
      p := PAnsiChar(Fred);
    
    In ASM:
    Unit7.pas.32: w := PWideChar(Fred);
    00462146 BFA4214600       mov edi,$004621a4     
    // no conversion, just a pointer to constant/"-1 RefCounted" UnicodeString
    
    Unit7.pas.33: p := PAnsiChar(Fred);
    0046214B BEB0214600       mov esi,$004621b0
    // no conversion, just a pointer to constant/"-1 RefCounted" AnsiString
    

    As you can see in both cases PWideChar/PChar(FRED) and PAnsiChar(FRED), there is no conversion and Delphi compiler make 2 constant strings, one AnsiString and one UnicodeString.

    0 讨论(0)
  • 2021-02-11 01:53

    Constants, including string literals, are untyped by default, and the compiler will fit them into whatever format works in the context you're using them in. As long as there are no non-ANSI characters in your string literal, the compiler won't have any trouble generating the string as ANSI instead of Unicode in this situation.

    0 讨论(0)
  • 2021-02-11 01:58

    For type-inferred constants (only initializable from literals) the compiler changes the actual text at compile-time, rather than at runtime. That means it knows whether or not the conversion loses data, so it doesn't need to warn you if it doesn't.

    0 讨论(0)
提交回复
热议问题