how to convert from LPCSTR to LPCWSTR in c++

后端 未结 2 1608
春和景丽
春和景丽 2020-12-20 16:54

additional info im building an application which use the WinHttpOpenRequest Api which requires LPCWSTR for the object name and im using visual studio 2008

相关标签:
2条回答
  • 2020-12-20 17:18

    Converting from char * has a nice sample

    char *orig = "Hello, World!";
    cout << orig << " (char *)" << endl;
    
    // Convert to a wchar_t*
    size_t origsize = strlen(orig) + 1;
    const size_t newsize = 100;
    size_t convertedChars = 0;
    wchar_t wcstring[newsize];
    mbstowcs_s(&convertedChars, wcstring, origsize, orig, _TRUNCATE);
    wcscat_s(wcstring, L" (wchar_t *)");
    wcout << wcstring << endl;
    

    But like tenfour mentioned. Use generic text mapping if possible

    0 讨论(0)
  • 2020-12-20 17:26

    The simplest way is to use ATL:

    #include <Windows.h>
    #include <atlbase.h>
    #include <iostream>
    
    int main(int argc, char *argv[]) {
        USES_CONVERSION;
        LPCSTR a = "hello";
        LPCWSTR w = A2W(a);
        std::wcout << w << std::endl;
        return 0;
    }
    

    Any memory allocated by A2W (ANSI to Wide) will be freed when the function exits.

    0 讨论(0)
提交回复
热议问题