gpt4 book ai didi

c++ - 传递从 std::string 转换为 wstring 的路径时,CreateProcess 失败

转载 作者:太空宇宙 更新时间:2023-11-04 12:14:04 25 4
gpt4 key购买 nike

我花了 2 个小时试图从 .ini 文件中读取我的路径字符串,以便与 CreateProcess 函数一起使用,该函数需要一个 LPCWSTR。出于某种原因,不管我怎么做,它就是行不通。

我有以下代码,我从另一个 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)

最佳答案

wchar_t* buf = new wchar_t[len];
MultiByteToWideChar(CP_ACP, 0, path.c_str(), slength, buf, len);
std::wstring wpath(buf);
delete[] buf;

我很确定这是不正确的。您应该调整 wstring 的大小并改用该缓冲区。

std::wstring wpath;
wpath.resize(len);
MultiByteToWideChar(CP_ACP, 0, path.c_str(), slength, &wpath[0], len);
CreateProcess(wpath.c_str(), ...

关于c++ - 传递从 std::string 转换为 wstring 的路径时,CreateProcess 失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8489647/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com