Reputation: 1680
I have a QString that I would like to convert into a char* not a QChar* because I'll be passing it into a method that takes a char*, however I can't convert it without it getting a const char*. For example I have tried:
QString name = "name";
QByteArray byteArray = name.toUtf8();
myMailboxName = byteArray.constData();
and
QString name = "name";
QByteArray byteArray = name.toUtf8();
myMailboxName = byteArray.data();
where myMailboxName is a private char* in my class. However I get an error because it is returning a const char* and can't assign it to a char*. How can I fix this?
Upvotes: 1
Views: 5292
Reputation: 75
try this code snippet
const char *myMailboxName = name.toLatin1().data();
Upvotes: 2
Reputation: 2988
consider following exampleQString str = "BlahBlah;"
try thischar* mychar = strdup(qPrintable(str));
or thischar* mychr = str.toStdString().c_str();
or thischar* mychar = strdup(str.ascii());
Every syntax worked for me ;)
Upvotes: 0
Reputation: 2385
I use something like this wrapper:
template<typename T, typename Y>
void CharPasser(std::function<T(char *)> funcToExecute, const Y& str)
{
char* c = 0;
c = qstrdup(c, str.c_str());
funcToExecute(c);
delete[] c;
}
int SomeFunc(char* ){}
then use it like:
CharPasser<int, std::string>(SomeFunc, QString("test").tostdString())
At least this saves a bit of typing... :)
Upvotes: 0
Reputation: 7181
You can really use strdup
(stackoverflow question about it), as Mike recommends, but also you can do that:
// copy QString to char*
QString filename = "C:\dev\file.xml";
char* cstr;
string fname = filename.toStdString();
cstr = new char [fname.size()+1];
strcpy( cstr, fname.c_str() );
Got there: stackoverflow similar question.
Upvotes: 1
Reputation: 702
Use strdup. It does the allocation and the copy at the same time. Just remember to free it once you're done.
Upvotes: 1
Reputation: 5874
This is because data() returns the address of the buffer in the bytearray, you can read it, but obviously you should not write it. You have your own buffer outside the bytearray. If you want the data, you should copy the buffer of bytearray into the myMailBoName.
use memcpy function
Upvotes: 3