使用std::string创建进程

4

我正在尝试使用std :: string创建CreateProcess,我几乎搜索了所有地方以找出如何将std :: string转换为LPSTR

我是C ++的新手

我正在制作GUI,当我点击按钮时,我想根据我输入的路径和我放置的32位或64位复选框启动程序。

对于客户端目录,我将System :: String ^更改为std :: string

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);

Try path:c_str() - user2100815
可能是重复的问题:无法将'std :: string'转换为'LPSTR' - TheKitchenSink
感谢 @TheKitchenSink。 - StokesMagee
2个回答

3

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

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

或者将path设置为std::wstring,并且在足够遥远的未来中使用CreateProcess(或CreateProcessW)和data,并且std::basic_string::data有了非const版本(这应该会在C++17中发生,但MSVC还没有赶上)。

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

CreateProcess的W版本可能会就地修改命令参数,这意味着您不应传递一个“只读”版本。奇怪的是,A版本不会这样做。


2
data()const 的伙计。 - Lightness Races in Orbit
1
@LightnessRacesinOrbit,这可能是我第一次因MSVC(希望是暂时的)不兼容而受到责备。幸运的是,答案的另一半仍然成立。 - zneak
1
A版本内部将字符串转换后调用W版本。该转换会将字符串复制到临时缓冲区,因此输入为const也就不足为奇了。 - MSalters

2

LPSTR代表长指针字符串。它等同于char[]或char*。

使用c_str()方法可以从std::string中获取char缓冲区。但是该缓冲区将是const的。

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

char* path = new char[exe.size() + 1] = {'\0'};   //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。有时它能够工作,但有时它却不能。原因是.NET存储字符串的方式与STL不同。我不会在这里详细介绍原因,因为这不是你的问题。当将托管字符串传递给本机字符串时,你应该始终首先使用marshal进行转换:

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

当从本地传递字符串到托管代码时,您不需要进行任何特殊处理。


重点是为了说明字符缓冲区的数据存储概念。数组的第一个元素的地址就是指针。 - plfoley

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接