How to convert LPBYTE to char */string in C++?

4.3k Views Asked by At

How do I convert LPBYTE into char * or string? Specifically, I am calling EnumPrinterDataEx(), and taking the pData out of it, and want to convert that. When I try to convert using wcstombs(), it only gives the first character from the pData. But I wanted to know how the conversion can be done in general.

Thanks

Edit: After getting the pData, I made a new variable of LPWSTR and then converted this into a char * using wcstombs, and it all worked well. Thanks!

2

There are 2 best solutions below

5
VitaliyG On

if pData points to a string than it will be ANSI or Unicode null terminated string (depending on EnumPrinterDataEx function version) - so you can simply cast it:

(char*)pData;
(LPTSTR)pData;
0
Bruno Ferreira On

It seems that your string is not multi-byte, so you have a wide string. Instead of manipulating it with common functions, use the wide versions, wcslen for example.

If conversion to a char* is required, then use wcstombs, like this:

#include <cstdlib>

size_t len = wcslen(input) * 2 + 1;
char * target = new char[len];
memset(target, 0, len);
if (wcstombs(target, input, len) == len) target[len - 1] = '\0';