Convert char[] to LPCWSTR

前端 未结 5 867
轻奢々
轻奢々 2020-11-30 13:05

Can anyone help me to correct this code:

    char szBuff[64];
    sprintf(szBuff, \"%p\", m_hWnd);
    MessageBox(NULL, szBuff, L\"Test print handler\", MB_O         


        
相关标签:
5条回答
  • 2020-11-30 13:07

    For this specific case, the fix is quite simple:

    wchar_t szBuff[64];
    swprintf(szBuff, L"%p", m_hWnd);
    MessageBox(NULL, szBuff, L"Test print handler", MB_OK);
    

    That is, use Unicode strings throughout. In general, when programming on Windows, using wchar_t and UTF-16 is probably the simplest. It depends on how much interaction with other systems you have to do, of course.

    For the general case, if you've got an ASCII (or char *) string, use either WideCharToMultiByte for the general case, or mbstowcs as @Matthew points out for simpler cases (mbstowcs works if the string is in the current C locale).

    0 讨论(0)
  • 2020-11-30 13:08

    You might want to look at mbstowcs, which will convert a conventional "one byte per character" string to a "multiple byte per character" string.

    Alternatively, change your project settings to use Multibyte Strings - by default they are usually "Unicode" or "Wide Character" strings (I can't remember the exact option name off the top of my head).

    0 讨论(0)
  • 2020-11-30 13:14

    If you are compiling with UNICODE, make all the strings you work with double width - i.e. define them as wchar_t*.

    If you really must convert ASCII to Unicode, use ATL conversion macros.

    0 讨论(0)
  • 2020-11-30 13:17

    Since your tag suggests VC++, I am suggesting CString. If yes, then the following snippet will also work for your case:

    CString szBuff;
    
    szBuff.Format(_T("%p"), m_hWnd);
    MessageBox(NULL, szBuff, L"Test print handler", MB_OK);
    
    0 讨论(0)
  • 2020-11-30 13:28

    Using MultiByteToWideChar() works for me:

    void main(int argc, char* argv[])
    {
     ...
     wchar_t filename[4096] = {0};
     MultiByteToWideChar(0, 0, argv[1], strlen(argv[1]), filename, strlen(argv[1]));
    
     // RenderFile() requires LPCWSTR (or wchar_t*, respectively)
     hr = pGraph->RenderFile(filename, NULL);
     ...
    }
    
    0 讨论(0)
提交回复
热议问题