I'm using the libxslt C library, and need to pass in parameters as const char *
. I'm wrapping the library in a Qt C++ class, so the parameters are stored in the C++ class are store as QMap<QString, QString>
.
My first attempt was simply:
const char *params[32];
int index = 0;
if (m_params.size() > 0) {
QMapIterator<QString, QString> it(m_params);
while (it.hasNext()) {
it.next();
params[index++] = it.key().toLocal8Bit().data();
params[index++] = it.value().toLocal8Bit().data();
}
}
params[index++] = nullptr;
qDebug() << params[0] << params[1]; // 0 0
But I realise that this isn't working because the QByteArray
from toLocal8bit
goes out of scope almost as soon as I've used it.
I've tried using strcpy - but have the same scope issues:
m_params.insert("some-key", "some-value", "another-key", "another-value");
if (m_params.size() > 0) {
QMapIterator<QString, QString> it(m_params);
while (it.hasNext()) {
it.next();
char buffer[32];
strcpy(buffer, it.key().toLocal8Bit().data());
params[index++] = buffer;
strcpy(buffer, it.value().toLocal8Bit().data());
params[index++] = buffer;
}
}
params[index++] = nullptr;
qDebug() << params[0] << params[1]; // another-value another-value
So now I have a list of params all with the same value.
When I set all the values manually, I get the expected outcomes:
const char *params[32];
int index = 0;
params[index++] = "something";
params[index++] = "something-else";
params[index++] = nullptr;
qDebug() << params[0] << params[1]; // something something-else