简体   繁体   中英

how to convert or cast CString to LPWSTR?

I tried to use this code:

USES_CONVERSION;
LPWSTR temp = A2W(selectedFileName);

but when I check the temp variable, just get the first character

thanks in advance

If I recall correctly, CString is typedef'd to either CStringA or CStringW , depending on whether you're building Unicode or not.

LPWSTR is a "Long Pointer to a Wide STRing" -- aka: wchar_t*

If you want to pass a CString to a function that takes LPWSTR, you can do:

some_function(LPWSTR str);

// if building in unicode:
some_function(selectedFileName);

// if building in ansi:
some_function(CA2W(selectedFileName));

// The better way, especially if you're building in both string types:
some_function(CT2W(selectedFileName));

HOWEVER LPWSTR is non-const access to a string. Are you using a function that tries to modify the string? If so, you want to use an actual buffer, not a CString.

Also, when you "check" temp -- what do you mean? did you try cout << temp ? Because that won't work (it will display just the first character):

char uses one byte per character. wchar_t uses two bytes per character. For plain english, when you convert it to wide strings, it uses the same bytes as the original string, but each character gets padded with a zero. Since the NULL terminator is also a zero, if you use a poor debugger or cout (which is uses ANSI text), you will only see the first character.

If you want to print a wide string to standard out, use wcout .

In short: You cannot. If you need a non-const pointer to the underlying character buffer of a CString object you need to call GetBuffer .

If you need a const pointer you can simply use static_cast<LPCWSTR>(selectedFilename) .

I know this is a decently old question, but I had this same question and none of the previous answers worked for me.

This, however, did work for my unicode build:

LPWSTR temp = (LPWSTR)(LPCWSTR)selectedFileName;

LPWSTR is a "Long Pointer to a Wide String". It is like wchar*.

CString strTmp = "temp";
wchar* szTmp;
szTmp = new WCHAR[wcslen(strTmp) + 1];
wcscpy_s(szTmp, wcslen(strTmp) + 1, strTmp);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM