CreateProcess with std::string

CreateProcess with std::string

本文关键字:string std with CreateProcess      更新时间:2023-10-16

我正在尝试使用std::string创建Process,我几乎到处搜索,以弄清楚如何将std::string转换为LPSTR

我是C++新手

我正在制作一个 GUI,当我单击一个按钮时,我想根据我输入的路径以及我输入的 32 位或 64 位复选框启动一个程序。

对于客户端目录,我将系统::字符串 ^ 更改为标准::字符串

std::string path = this->getClientDirectory(); // Get the directory that the user has set
// Get the EXE bit that the user has ticked.
std::string exe;
if (this->isClient32Ticked)
exe = "client_x32.exe";
else
exe = "client_x64.exe";
//add the exe name to the end of the string.
path.append("\");
path.append(exe);
CreateProcess(NULL, path, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL);

您需要将c_str方法与CreateProcessA一起使用......

CreateProcessA(NULL, path.c_str(), NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL);

或者path成为std::wstring,并将dataCreateProcess(或CreateProcessW(一起使用,并生活在一个足够遥远的未来,std::basic_string::data有一个非const版本(这应该发生在 C++17,但 MSVC 还没有赶上它(。

CreateProcessW(NULL, path.data(), NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL);

CreateProcess 的 W 版本可能会就地修改命令参数,这意味着不应传递它的"只读"版本。奇怪的是,A版本没有。

LPSTR 代表 Long Pointer STRing。它等效于 char[] 或 char*。

可以使用c_str(( 方法从 std::string 获取 char 缓冲区。但这种缓冲将是恒定的。

这里你必须做的是分配一个 char 的非常量缓冲区,并将 std::string const-char 缓冲区复制到其中。

char* path = new char[exe.size() + 1] = {''};   //Create the non-const char buffer initialized with zero characters
strncpy(path, exe.c_str(), exe.size());           //Copy the content from exe to path
CreateProcess(NULL, path, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL);
delete path[];

我还在您的帖子中看到了一些可能会导致您出现问题的内容:

您提到将System::String^转换为std::string的事实。有时这会起作用,有时不会。原因是与 STL 相比,.NET 存储字符串的方式。我不会在这里详细介绍原因,因为这不是你的问题。将托管字符串传递给本机字符串时,应始终首先使用以下命令对其进行封送:

System::Runtime::InteropServices::Marshal::StringToHGlobalAnsi(System::String^)

将字符串从本机传递到托管时,无需执行任何特殊操作。