如何在C++中将std :: wstring转换为LPCTSTR?

Ern*_*dis 19 c++ string type-conversion wstring

我有wstring格式的Windows注册表键值.现在我想将它传递给这个代码(第一个参数 - javaw.exe的路径):

std::wstring somePath(L"....\\bin\\javaw.exe");

    if (!CreateProcess("C:\\Program Files\\Java\\jre7\\bin\\javaw.exe", <--- here should be LPCTSTR, but I have a somePath in wstring format..
            cmdline, // Command line.
            NULL, // Process handle not inheritable.
            NULL, // Thread handle not inheritable.
            0, // Set handle inheritance to FALSE.
            CREATE_NO_WINDOW, // ON VISTA/WIN7, THIS CREATES NO WINDOW
            NULL, // Use parent's environment block.
            NULL, // Use parent's starting directory.
            &si, // Pointer to STARTUPINFO structure.
            &pi)) // Pointer to PROCESS_INFORMATION structure.
    {
        printf("CreateProcess failed\n");
        return 0;
    }
Run Code Online (Sandbox Code Playgroud)

我怎样才能做到这一点?

pau*_*ulm 26

只需使用的c_str功能std::w/string.

看这里:

http://www.cplusplus.com/reference/string/string/c_str/

std::wstring somePath(L"....\\bin\\javaw.exe");

    if (!CreateProcess(somePath.c_str(),
            cmdline, // Command line.
            NULL, // Process handle not inheritable.
            NULL, // Thread handle not inheritable.
            0, // Set handle inheritance to FALSE.
            CREATE_NO_WINDOW, // ON VISTA/WIN7, THIS CREATES NO WINDOW
            NULL, // Use parent's environment block.
            NULL, // Use parent's starting directory.
            &si, // Pointer to STARTUPINFO structure.
            &pi)) // Pointer to PROCESS_INFORMATION structure.
    {
        printf("CreateProcess failed\n");
        return 0;
    }
Run Code Online (Sandbox Code Playgroud)

  • 然后使用std :: string或调用CreateProcessW而不是CreateProcessA (3认同)
  • 这是行不通的:无法将参数'1'的'const wchar_t *'转换为'LPCSTR {aka const char *}'到'BOOL CreateProcessA(LPCSTR,LPSTR,LPSECURITY_ATTRIBUTES,LPSECURITY_ATTRIBUTES,BOOL,DWORD,PVOID,LPCSTR,LPSTARTUPINFOA, LPPROCESS_INFORMATION)” (2认同)
  • 如果`LPCTSTR`是`const char*`那么就没有理由你应该使用`std :: wstring`.相反,如果您认为应该使用`std :: wstring`,请在项目选项中设置`UNICODE`标志. (2认同)

Lih*_*ihO 9

LPCTSTR是一个古老的遗物.它是一个混合类型定义,可以定义char*您是使用多字节字符串还是wchar_t*使用Unicode.在Visual Studio中,可以在"字符集"下的常规项目设置中更改此设置.

如果您使用的是Unicode,那么:

std::wstring somePath(L"....\\bin\\javaw.exe");
LPCTSTR str = somePath.c_str();                 // i.e. std::wstring to wchar_t*
Run Code Online (Sandbox Code Playgroud)

如果您使用多字节,请使用此帮助程序:

// wide char to multi byte:
std::string ws2s(const std::wstring& wstr)
{
    int size_needed = WideCharToMultiByte(CP_ACP, 0, wstr.c_str(), int(wstr.length() + 1), 0, 0, 0, 0); 
    std::string strTo(size_needed, 0);
    WideCharToMultiByte(CP_ACP, 0, wstr.c_str(), int(wstr.length() + 1), &strTo[0], size_needed, 0, 0); 
    return strTo;
}
Run Code Online (Sandbox Code Playgroud)

std::wstring,以std::string将包含多字节的字符串,然后到char*:

LPCTSTR str = ws2s(somePath).c_str();
Run Code Online (Sandbox Code Playgroud)