首页 > 解决方案 > 如何将 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崩溃!

在此处输入图像描述

你能告诉我我做错了什么吗?

标签: c++qtc-stringsqstring

解决方案


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

推荐阅读