CreateProcess with std::string
CreateProcess with std::string
我正在尝试使用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
,并将data
与CreateProcess
(或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^)
将字符串从本机传递到托管时,无需执行任何特殊操作。
- cppcheck在const std::string[]上引发警告
- 将std::string传递给WriteConsole API
- 为std::string的某个索引赋值
- std中有类似find_last_of的函数,而string中没有
- 使用 std::string () const 函数启动线程或未来
- 当我们进行一些操作时,应该使用什么'std::string'或'std::stringstream'?
- 如何更改大小(std::string)
- std::string 的对象真的可以移动吗?
- SegFault 同时使用 std::string::operator+= 和函数作为参数
- 无法从 std::string 中提取C++ Unicode 符号
- std::string 构造函数如何处理固定大小的 char[]?
- 确切地说,如何解释 std::getline(stream, string) 函数在C++中填充的字符串
- C++:考虑C++ std::string 中双引号 (") 的字面含义,而不使用反斜杠 (\)
- 'int main(int, int, std::__cxx11::string, std::__cxx11::string)'只需要零或两个参数 [-Wmain]
- C++ 在列表和列表之间选择返回类型<<string>std::p air<string,string>>
- std::string, std::wstring and UTF8
- uan inplace replacement of std::string/std::wstring?
- #define Glib::string std:wstring
- 从 std::string & std::wstring 中获取 char 整数值
- BSTR转换为std::string(std::wstring),反之亦然