Windows Dialog : how to convert type PWSTR to char*?

140 Views Asked by At

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.

1

There are 1 best solutions below

1
QuishKa On

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