cpointerswinapilpcwstrlpbyte

Struggling with conversion of an LPBYTE to char* or anything alike in C (Chinese output?)


I've got a C project that I'm working on and I'm having a problem. The program reads a string that is echoed by a .php page. It uses this code to read the data and appoint it to a variable, which get sent to the Commands() function:

LPSTR szBuffer=(LPSTR)chunk+0x1000;
DWORD dwRead;

if (CWA(_HttpSendRequestA, wininet, hHttpRequest, szHeaders, lpstrlenA(szHeaders), szReq, lpstrlenA(szReq)) != 0)
    {
        CWA(_InternetReadFileA, wininet, hHttpRequest, szBuffer, 0x400, &dwRead);
        if (dwRead)
            Commands((LPBYTE)szBuffer, dwRead);
    }

As you can see the data is sent to the Commands() function, which receives the LPBYTE szBuffer (named "command" in the function) and the DWORD dwRead (named "size" in the function).

In the Commands() function, it's supposed to read the string that it read from the .php page. However, since the data seems to be stored as LPBYTE, I've done a lot of things trying to get that to a char*. When I thought I had finally got it however, I tried outputting it using a MessageBox (to see if it displays the string it should have read). However, this returns me Chinese characters (while the original string should be this:

"TASKci=0C73CCFD206BBD011E7087CE0806E6F6E69630,job=dlex,ti=AD62A5950B76F3812C542C24040EACE9,pr=https,ur=//test.com/test.txt,cl=".

Screenshot of what it returns me: http://prntscr.com/h0p5iw

How the code inside Commands() looks:

BOOL Commands(LPBYTE command, DWORD size) {

LPTSTR x = (LPTSTR)((char*)command);

{

        int msgboxID = MessageBox(
        NULL,
        x,
        (LPCWSTR)L"Woop",       
        MB_ICONWARNING | MB_CANCELTRYCONTINUE | MB_DEFBUTTON2 );

}


CWA(Sleep, kernel32, 100);

return 1; }

I'm new at C (I've only written stuff in C# before) so I am sorry if I am asking any dumb questions, I've really tried my best but I cannot seem to find any solution by myself.

Also, keep in mind that everything except for the stuff inside the Commands() function is not coded by me but by someone who is way more experienced. That code should be fine and I am sure that it is reading the data from the page, it's probably just me screwing up a conversion somewhere.


Solution

  • A narrow string (char*) tends to look like Chinese when you use it somewhere that expects a wide UTF-16 Unicode string.

    You cannot just cast the string to change its type, you need to call MultiByteToWideChar.