c++ - 如何将 QString 转换为 char**
问题描述
我想从我的 Qt 应用程序中调用一个外部程序。这需要我为外部命令准备一些参数。这就像从终端调用另一个进程一样。例如:
app -w=5 -h=6
为了测试这一点,我有一个简单的功能,例如:
void doStuff(int argc, char** argv){ /* parse arguments */};
我尝试准备一组这样的参数:
QString command;
command.append(QString("-w=%1 -h=%2 -s=%3 ")
.arg("6").arg("16").arg(0.25));
command.append("-o=test.yml -op -oe");
std::string s = command.toUtf8().toStdString();
char cstr[s.size() + 1];
char* ptr = &cstr[0];
std::copy(s.begin(), s.end(), cstr);
cstr[s.size()] = '\0';
然后我调用该函数:
doStuff(7, &cstr);
但是我在 debuggre 和我的解析器(opencvCommandLineParser
崩溃!
你能告诉我我做错了什么吗?
解决方案
doStuff
期待一个字符串数组而不是单个字符串。
像这样的东西应该工作:
std::vector<std::string> command;
command.push_back(QString("-w=%1").arg("6").toUtf8().toStdString());
command.push_back(QString("-h=%2").arg("16").toUtf8().toStdString());
command.push_back(QString("-s=%3").arg("0.25").toUtf8().toStdString());
command.push_back("-o=test.yml");
command.push_back("-op");
command.push_back("-oe");
std::vector<char*> cstr;
std::transform(command.begin(), command.end(), std::back_inserter(cstr),[](std::string& s){return s.data();});
doStuff(cstr.size(), cstr.data());
推荐阅读
- linux - 如何在 vscode 上打字更快?
- php - 通过 laravel 将多表行插入数据库
- sequelize.js - 在 hasMany 关联上使用 set 时出错
- reactjs - 将react hooks和context的reducer与类型安全结合起来
- docker - 列出 Docker Hub 上的存储库名称
- azure-devops - 在 Azure Devops 中,我希望我的 yaml 管道仅在同一管道的上一次执行完成后执行
- vue.js - 如何在 Azure DevOps YAML 中配置 ESLint 设置?
- firebase - 部署错误。服务器错误。连接 ETIMEDOUT
- server - 服务器无法正常启动。[2020-04-25T07:05:35.422Z] 错误 (hook:bookshelf) 加载时间过长 (hook:bookshelf) 加载时间过长
- regex - 正则表达式匹配具有重复序列的单词和数字 (FOO-123 / FOO-456 /...等)