Search code examples
c++qtc-stringsqstring

how to convert QString to char**


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!

enter image description here

Can you please tell me what am I doing wrong?


Solution

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