0

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!

NV Bhargava
  • 373
  • 2
  • 10
  • Well, this depends on the encoding of the data! You'll have to do some string sniffing to guess if it's UTF-8 or UTF-16 or something more esoteric... – Cameron May 23 '14 at 17:01

2 Answers2

1

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;
VitaliyG
  • 1,837
  • 1
  • 11
  • 11
  • thanks for the reply. I tried it both ways, but (char *) gives only the first character. (LPTSTR) gives some garbage value, or might not be garbage but something I have no clue of what it is. – NV Bhargava May 23 '14 at 17:24
  • Are you sure pData points to string? Can you view memory pointed by pData. What is the value of (char*)pData[0], (char*)pData[1]...Try also (wchar_t*)pData. – VitaliyG May 23 '14 at 17:31
  • It crashes for (char *)pData[0], (char *)pData[2].. And (wchar_t*)pData returns some garbage value. The actual value of pData when I do wprintf() is of the form "AB1CD-E2FGH" – NV Bhargava May 23 '14 at 17:39
  • What is the value of cbData. You should be able to view up to (char*)pData[cbData-1] is this not true than your pData is not pointing to valid memory – VitaliyG May 23 '14 at 17:52
  • cbData is 58. Although as you above said, I converted into LPWSTR, and then changed it to char * using wcstombs, and then it all worked perfectly. Thank you so much for your time! – NV Bhargava May 23 '14 at 17:59
0

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';
Bruno Ferreira
  • 1,621
  • 12
  • 19