c ++ createprocess - 命令行参数的字符串var - 没有任何反应

c++ createprocess - string var for cmd line parameter - nothing happening

所以我正在尝试使用字符串变量创建一个进程。

STARTUPINFO si;
PROCESS_INFORMATION pi;
ZeroMemory(&si, sizeof(si));
ZeroMemory(&pi, sizeof(pi));

si.cb = sizeof(si);

std::string cmd_line = game_path + " " + std::string(game_params);

std::cout << cmd_line << "\n";

if (!CreateProcess(NULL, LPTSTR(cmd_line.c_str()), NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi)) {
    std::cout << "fail\n";
    return false;
}

cout cmd_line 的输出是正确的路径和参数:

C:\Program Files (x86)\My_Game\Game.exe -test -admin

createprocess 调用返回 false,但我不确定具体原因。我对此很陌生,所以任何帮助和建议都会很棒。

int _tmain(int argc, _TCHAR* argv[])
{
    STARTUPINFO si;
    PROCESS_INFORMATION pi;
    ZeroMemory(&si, sizeof(si));
    ZeroMemory(&pi, sizeof(pi));

    si.cb = sizeof(si);

    std::string game_path = "C:\Windows\system32\calc.exe";
    std::string game_params = "-test -admin";

    std::string cmd_line = game_path + " " + std::string(game_params);

    std::cout<<cmd_line << "\n";

    TCHAR tszCmdLine[1024] = {0};
    mbstowcs(tszCmdLine, cmd_line.c_str(), 1024);
    _tprintf(tszCmdLine);

    if (!CreateProcess(NULL, tszCmdLine, NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi)) {
        std::cout<<"fail\n"<<GetLastError();
        return false;
    }
}

const char* 不能作为 CreateProcess() 的参数。您必须使用 mbstowcs()

char* 字符串转换为 tchar* 字符串

我测试了你的代码。

GetLastError()的结果是2。

The system cannot find the file specified.

使用MultiByteToWideCharchar*字符串转换为TCHAR*字符串。

MultiByteToWideChar(LC_ALL, 0, cmd_line.c_str(), -1, str_command, MAX_PATH);