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

时间:2011-12-13 12:56:59

标签: c++ string wstring

我花了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)

1 个答案:

答案 0 :(得分:1)

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(), ...