当传递从 std::string 转换为 wstring 的路径时,CreateProcess 失败
我花了 2 个小时尝试从 .ini 文件中读取路径字符串,以便与需要 LPCWSTR
的 CreateProcess
函数一起使用。出于某种原因,无论我怎么做,它就是行不通。
我有以下代码,这是我从另一个 SO 答案中获取的,并进行了修改以供我使用,但是 CreateProcess
仍然无法启动该过程。
有人可以帮忙吗?
std::ifstream file(file_path.c_str());
settings new_settings;
if(file.is_open() && !file.fail())
{
std::string key;
char sign = '=';
std::string value;
std::string line;
while(!file.eof())
{
std::getline(file, key, sign);
std::getline(file, value);
//fill in settings struct with `value` variable. Struct contains only `std::string` types.
}
}
file.close();
PROCESS_INFORMATION proc_info;
STARTUPINFO start_info;
memset(&start_info, 0, sizeof(start_info));
start_info->cb = sizeof(STARTUPINFO);
std::string path = "C:\\Mydir\\myexe.exe";
int len;
int slength = (int)path.length() + 1;
len = MultiByteToWideChar(CP_ACP, 0, path.c_str(), slength, 0, 0);
wchar_t* buf = new wchar_t[len];
MultiByteToWideChar(CP_ACP, 0, path.c_str(), slength, buf, len);
std::wstring wpath(buf);
delete[] buf;
LPCWSTR p_path = wpath.c_str();
created = CreateProcess(p_path, lpPort, 0,0, FALSE, CREATE_NEW_CONSOLE,NULL,NULL,&start_info ,&proc_info);
DWORD dwErr = GetLastError(); //Returns 0x7b (Invalid Path Or FileName)
I have been spending 2 hours trying to get my path string read from a .ini file to work with the CreateProcess
function, which expects a LPCWSTR
. For some reason, no matter how I do it, it just will not work.
I have the following code, which I've taken from another SO answer, and amended for my use, however CreateProcess
still doesn't start the process.
Can anybody help?
std::ifstream file(file_path.c_str());
settings new_settings;
if(file.is_open() && !file.fail())
{
std::string key;
char sign = '=';
std::string value;
std::string line;
while(!file.eof())
{
std::getline(file, key, sign);
std::getline(file, value);
//fill in settings struct with `value` variable. Struct contains only `std::string` types.
}
}
file.close();
PROCESS_INFORMATION proc_info;
STARTUPINFO start_info;
memset(&start_info, 0, sizeof(start_info));
start_info->cb = sizeof(STARTUPINFO);
std::string path = "C:\\Mydir\\myexe.exe";
int len;
int slength = (int)path.length() + 1;
len = MultiByteToWideChar(CP_ACP, 0, path.c_str(), slength, 0, 0);
wchar_t* buf = new wchar_t[len];
MultiByteToWideChar(CP_ACP, 0, path.c_str(), slength, buf, len);
std::wstring wpath(buf);
delete[] buf;
LPCWSTR p_path = wpath.c_str();
created = CreateProcess(p_path, lpPort, 0,0, FALSE, CREATE_NEW_CONSOLE,NULL,NULL,&start_info ,&proc_info);
DWORD dwErr = GetLastError(); //Returns 0x7b (Invalid Path Or FileName)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我相当确定这是不正确的。您应该调整
wstring
的大小并使用该缓冲区。I'm fairly sure this is incorrect. You should resize the
wstring
and use that buffer instead.