简体   繁体   English

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

[英]CreateProcess fails when passed a path converted from std::string to wstring

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 . 我已经花了2个小时试图从.ini文件中读取我的路径字符串,以使用CreateProcess函数,该函数需要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. 我有以下代码,该代码是我从另一个SO答案中获取的,并已针对我的使用进行了修改,但是CreateProcess仍然无法启动该过程。

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)
wchar_t* buf = new wchar_t[len];
MultiByteToWideChar(CP_ACP, 0, path.c_str(), slength, buf, len);
std::wstring wpath(buf);
delete[] buf;

I'm fairly sure this is incorrect. 我相当确定这是不正确的。 You should resize the wstring and use that buffer instead. 您应该调整wstring大小并改用该缓冲区。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM