Reputation: 911
I want to call an external program from my Qt application. This requires me to prepare some arguments for the external command. This will be just like calling another process from terminal. E.g.:
app -w=5 -h=6
To test this, I have a simple function like:
void doStuff(int argc, char** argv){ /* parse arguments */};
I try to prepare a set of arguments like this:
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';
Then I call that function:
doStuff(7, &cstr);
But I get the wrong argumetns (corrupted) in the debuggre and my parser (opencv CommandLineParser
crashes!
Can you please tell me what am I doing wrong?
Upvotes: 1
Views: 386
Reputation: 36389
doStuff
is expecting an array of strings not a single string.
Something like this should work:
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());
Upvotes: 2
Reputation: 9354
Because you need to split your space separated string into individual strings for arguments.
argv points to an array of strings - what you need to end up with is something like
argv[0] -> "-w=6"
argv[1] -> "-h=16"
...
argv[7] -> 0
which writing the string over your char array isn't going to achieve, as thats just treating cstr as an array of characters.
Upvotes: 1