L prefix for strings in C++

前端 未结 5 1565
遇见更好的自我
遇见更好的自我 2021-01-05 10:45

I have a static library. This library have the following function defined

int WriteData(LPTSTR s)

The sample to call the function is

5条回答
  •  野趣味
    野趣味 (楼主)
    2021-01-05 11:02

    The specific "function" to perform the L prefix is a macro TEXT() or _T(). (TEXT is defined by the Windows SDK, _T is an extension of the Microsoft C Runtime).

    These functions automatically add the L prefix when your project is built with unicode support on (which is the default for new projects now in most MS Dev environments) - or leave it off for non unicode (or ansi) configured projects.

    Don't do this cast:

    LPTSTR s = (LPTSTR) L"ABC";   // Working fine
         WriteData(s);
    

    If the project was ever configured for non Unicode, then L"ABC" would still be an array of wide-characters, but LPTSTR would become a pointer to an array of 8bit characters.

    This is how to correctly assign a string to an Ansi, Unicode, or "Text" string. (Text can be Ansi or Unicode depending on project settings) (I left off the L because its redundant, and added a C, because string literals should be constant).

    PCSTR p1 = "ABC";
    PCWSTR p2 = L"ABC";
    PCTSTR p3 = TEXT("ABC");
    

提交回复
热议问题