gpt4 book ai didi

c++ - .c_str() 未按预期运行

转载 作者:行者123 更新时间:2023-11-30 03:36:06 29 4
gpt4 key购买 nike

我想创建一个进程来读取一些串口。但是,用户将来应该能够更改程序所在的路径。这就是为什么我想包含变量 BasePathFile,它在类的初始化过程中设置为默认值:

const std::string BP = "C:\\aerospec_developement\\";
...
BasePathFile = BP;
...

有人可以解释为什么//1 不起作用,但//2 可以吗

void AerospecGUI::ReadPressure()
{
//1 const char *Args = ("C:\\Windows\\System32\\cmd.exe /C powershell /C "+ BasePathFile+"sourcecode\\pressure.ps1 -comport COM4 -baud 1200 -parity None -data 8 -stopbits one").c_str();
//2 const char *Args = "C:\\Windows\\System32\\cmd.exe /C powershell /C C:\\aerospec_developement\\sourcecode\\pressure.ps1 -comport COM4 -baud 1200 -parity None -data 8 -stopbits one";

STARTUPINFO StartupInfo;
PROCESS_INFORMATION ProcessInfo;
memset(&StartupInfo, 0, sizeof(StartupInfo));
memset(&ProcessInfo, 0, sizeof(ProcessInfo));
StartupInfo.cb = sizeof(StartupInfo);
wchar_t wargs[1000];
mbstowcs(wargs, Args, strlen(Args)+1);//Plus null
LPWSTR argsptr = wargs;

bool result = CreateProcess(NULL, argsptr, NULL, NULL, FALSE, NULL, NULL, NULL,
&StartupInfo, &ProcessInfo);
...

此外,作者在另一个函数中写了非常相似的一行。但这个有效。

bool AerospecGUI::FTP(std::string command, std::string file)
{
// This function executes a batch script with the given parameters. The batch script
// generates a .ftp file which contains the commands to perform the action given by "command"
// (get, put, delete).
const char *Args = ("C:\\Windows\\System32\\cmd.exe /C "+BasePathFile +"FTP\\FileTransfer.bat " + ServerURL + " root password " + command + " " + BasePathFile + "FTP\\ " + file +" " + BasePathFile + "FTP\\" + file.substr(0,file.size()-4)+".ftp").c_str();
STARTUPINFO StartupInfo;
PROCESS_INFORMATION ProcessInfo;
memset(&StartupInfo, 0, sizeof(StartupInfo));
memset(&ProcessInfo, 0, sizeof(ProcessInfo));
StartupInfo.cb = sizeof(StartupInfo);
wchar_t wargs[1000];
mbstowcs(wargs, Args, strlen(Args)+1);//Plus null
LPWSTR argsptr = wargs;
...

最佳答案

1 和原作者代码是错误的:c_str() 返回一个类 C 字符串的指针,但它是 std 的成员函数::string 类(参见 docs )。在 std::string 对象过期后取消引用其指针是未定义的行为(可能有效也可能无效)。

2 可以正常工作

const char *Args = "C:\\... one";

因为它是一个字符串文字,并且它的生命周期跨越整个程序执行。

关于c++ - .c_str() 未按预期运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40840095/

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