Luis Gabriel Fabres
Luis Gabriel Fabres

Reputation: 133

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

Upvotes: 3

Views: 20711

Answers (4)

Rango22
Rango22

Reputation: 76

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);

Upvotes: 0

Tim
Tim

Reputation: 9172

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.

Upvotes: 8

James Mart
James Mart

Reputation: 640

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;

Upvotes: 1

IInspectable
IInspectable

Reputation: 51420

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).

Upvotes: 1

Related Questions