gpt4 book ai didi

c++ - 将项目转换为支持 Unicode 后,CreateProcess 不运行 .cmd 文件

转载 作者:行者123 更新时间:2023-11-28 06:43:40 25 4
gpt4 key购买 nike

我更改了一个旧的 MFC 应用程序以支持 Unicode。现在代码如下所示。基本上我在这里调用一个 .cmd 文件:

STARTUPINFO StartupInfo;
DWORD dwErrorCode;

PROCESS_INFORMATION * processInformation = new PROCESS_INFORMATION[2];

for (int i = 0; i < 2; i++)
{
GetStartupInfo(&StartupInfo);

if (processList[i].bHide)
{
StartupInfo.dwFlags |= STARTF_USESHOWWINDOW;
StartupInfo.wShowWindow = SW_HIDE;
}

if (processList[i].sCustomTitle.GetLength())
StartupInfo.lpTitle = processList[i].sCustomTitle.GetBuffer(processList[i].sCustomTitle.GetLength());

CreateProcess(NULL,
/*I changed LPSTR to LPWSTR*/(LPWSTR)(LPCTSTR)processList[i].sCommandLine,
NULL, NULL, TRUE, NORMAL_PRIORITY_CLASS, NULL, NULL, &StartupInfo, &processInformation[i]);

[...]
}

我所做的唯一更改是将 LPSTR 更改为 LPWSTR。在转换为 Unicode 之前,这是没有任何问题的。但是现在它没有运行。可能是什么原因?在转换为 Unicode 支持时,我是否遗漏了任何需要完成的事情?

P.S.:我调试检查了所有的参数。他们看起来很好。 sCommandLinePROCESS_STARTUP_INFO 结构 中的一个 CString 变量。

最佳答案

如评论中所述,您不应转换字符串。您应该使用临时变量,因为 documentation 中的以下注释:

The Unicode version of this function, CreateProcessW, can modify the contents of this string. Therefore, this parameter cannot be a pointer to read-only memory (such as a const variable or a literal string). If this parameter is a constant string, the function may cause an access violation.

最近我遇到了类似的问题。我通过以下方式解决了它(我试图让它防弹):

// The maximum length of the command line string is 32,768 characters,
// including the Unicode terminating null character.
#define MAX_CMD_LINE_LEN 32768

// Use a temporary variable for the command line.
TCHAR szCmdLine[MAX_CMD_LINE_LENGTH];

// Get the length of the command line. Crop the command line if it is too long.
int iLen = min(processList[i].sCommandLine.GetLength(), MAX_CMD_LINE_LEN - 1);

// Copy the command line string to the temporary variable.
_tcsncpy_s(szCmdLine, processList[i].sCommandLine, iLen);

// Create the process by passing the temporary variable holding a copy of your
// original command line string.
CreateProcess(NULL,
szCmdLine,
NULL, NULL, TRUE, NORMAL_PRIORITY_CLASS, NULL,
NULL, &StartupInfo, &processInformation[i]);

此解决方案应该编译并适用于 Unicode 和非 Unicode 版本。

关于c++ - 将项目转换为支持 Unicode 后,CreateProcess 不运行 .cmd 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25439783/

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