如何将 QString 转换为 char**

how to convert QString to 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()] = '[=12=]';

然后我调用那个函数:

doStuff(7, &cstr);

但是我在 debuggre 和我的解析器中得到了错误的参数(损坏)(opencv CommandLineParser 崩溃了!

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

因为您需要将 space 分隔的字符串拆分为单独的参数字符串。

argv 指向一个 字符串数组 - 你最终需要的是

argv[0] -> "-w=6"
argv[1] -> "-h=16"
...
argv[7] -> 0

在 char 数组上写入字符串不会实现,因为那只是将 cstr 视为字符数组。

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