-1

I am using a Windows Dialog to select a file. The output type I receive is a PWSTR. Whenever I've tried to convert it to char*, all I get is the first character of the string (ie 'C').

For some context, my variable name is pszFilePath. I have used multiple casting types, like using reinterpret_cast, static_cast, and (char*)pszFilePath. All of which either do not work, or cause an error.

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
  • 2
    On Windows a wide character is commonly two bytes, and the characters are stored in UTF-16 encoding. A simple cast will not convert each character from something that can be displayed as narrow characters. Generally, if you ever feel the need to do a C-style cast (like `(char *) ...`) then you should take it as a sign that you're probably doing something wrong. There are functions that can convert wide-character strings into their corresponding narrow character representation. But generally, don't mix wide and narrow character functions. Use one or the other, *always*. – Some programmer dude Jul 29 '23 at 21:08
  • https://learn.microsoft.com/en-us/windows/win32/api/stringapiset/nf-stringapiset-widechartomultibyte – Paul Sanders Jul 29 '23 at 21:10
  • 3
    Chances are high you do **not** want to actually perform this conversion, but work with the string in its original, wide character format. For further assistance, prepare a [mcve]. – Igor Tandetnik Jul 29 '23 at 21:17
  • Or https://learn.microsoft.com/en-us/cpp/c-runtime-library/reference/wcstombs-wcstombs-l. – CristiFati Jul 29 '23 at 22:37
  • Have a look at this C++ (non-windows API version) https://en.cppreference.com/w/cpp/string/multibyte/wcsrtombs. But know conversion can do all kind of stuff dependent on locale settings. (only kind of works reproducibly on what in the end will be `ASCII` characters) – Pepijn Kramer Jul 30 '23 at 05:02
  • Depending on which dialog API you are actually using, there may be an ANSI version available that outputs `char` strings instead of `wchar_t` strings. – Remy Lebeau Jul 30 '23 at 08:28

1 Answers1

0

PWSTR is a wchar_t* string

https://learn.microsoft.com/en-us/windows/win32/learnwin32/working-with-strings

So you need to convert wchar_t* to char*. wcstombs(mbstring,wcstring,N) from stdlib.h does exactly that.

About converting only first character of your string, I guess you use something like sizeof(var) / sizeof(PWSTR) to allocate memory for your char* string but it doesn't work this way. I don't really know how to get the length of PWSTR since strlen() doesn't work with wchar_t*, so you need some struct that will count it or anything else.

Example

PWSTR pw = new wchar_t;
PCWSTR pcw = L"qwe\n\0";
wcscpy(pw, pcw);
char *c = (char*)malloc(sizeof(char) * 5);
wcstombs(c, pw, 5);
printf("%s", c);
  • The [`wcslen`](https://en.cppreference.com/w/c/string/wide/wcslen) function is the standard equivalent of `strlen` for `wchar_t` strings. – Adrian Mole Aug 06 '23 at 12:56