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

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

最佳答案

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/

相关文章:

ios - 获取 NSString 在字符串中的位置 - iOS

c++ - 在 Const char string[] 上使用字符串函数

Visual Studio 2012 : LPCWSTR and wstring 中的 C++ 编译错误

android-ndk - Android NDK 中缺少 std::wstring 支持的解决方案?

c++ - 为什么我的重载转换运算符无法访问私有(private)成员?

C++ 使用 *this 属性调用单个辅助函数

c++ - #import 等效命令行

regex - 从 Perl 中的字符串中删除换行符

C++ 错误(将 wstring 转换为字符串):无法将参数 1 从 std::wchar_t 转换为 std::char

c++ - 将 std::function 与模板一起使用