Can someone explain to me these data types WSTR ,LPCWSTR and how to initialize them?

Ioann 61 Reputation points
2022-01-24T18:52:19.717+00:00

Can someone explain to me these data types WSTR ,LPCWSTR and how to initialize them?

There is a function that needs a LPCWSTR input.

Developer technologies | C++
0 comments No comments
{count} votes

Accepted answer
  1. Michael Taylor 60,326 Reputation points
    2022-01-24T20:56:12.933+00:00

    WSTR stands for wide string or otherwise known as a Unicode string. But note that generally you'll see LPWSTR as strings are pointers in C++. How you get one depends upon several things. If your code is compiling for ANSI then you'll likely only get this if you call wide string functions. If you need to convert from an ANSI string to a Unicode one you have to use one of the Win32 conversion functions. If you're compiling for Unicode you're already going to be using the LPWSTR types.

    If you have a string literal then you can tell the compiler it is a Unicode string using the L prefix.

       //ANSI  
       "Hello"  
         
       //Unicode  
       L"Hello"  
         
       //ANSI or Unicode, depends on compilation  
       T("Hello")  
    

    If you need to compile for either ANSI or Unicode then you need to use LPTSTR instead so the compiler choses the correct type.

    LP stands for long pointer which is just a pointer in modern processors. Since strings in C++ are character arrays and hence pointers you will either use the standard STL string type (or equivalent) or you'll stick with C-style strings and you'll be using LPSTR, LPTSTR or perhaps LPWSTR for your types. They are mean pointer to a string (Ansi, Either, Unicode).

    The C in the middle means a constant pointer meaning the string cannot be changed. Many functions require an LPCSTR, LPCTSTR or LPCWSTR which means a pointer to a constant (Ansi, either, Unicode) string. The callee won't be able to modify the string. Typically you can just pass a string literal here (which is constant).

       //void Foo ( LPCWSTR name )  
       Foo(L"Bob");  
    
    0 comments No comments

1 additional answer

Sort by: Most helpful
  1. Castorix31 90,686 Reputation points
    2022-01-24T19:27:47.59+00:00
    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.