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)
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)