简体   繁体   English

我如何将QString转换为char *

[英]How do i convert a QString to a char*

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*. 我有一个要转换为char *而不是QChar *的QString,因为我会将其传递给采用char *的方法,但是如果没有得到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. 其中myMailboxName是班上的私有char *。 However I get an error because it is returning a const char* and can't assign it to a char*. 但是我收到一个错误,因为它返回一个const char *并且不能将其分配给char *。 How can I fix this? 我怎样才能解决这个问题?

This is because data() returns the address of the buffer in the bytearray, you can read it, but obviously you should not write it. 这是因为data()返回字节数组中缓冲区的地址,您可以读取它,但是显然您不应该编写它。 You have your own buffer outside the bytearray. 您在字节数组之外有自己的缓冲区。 If you want the data, you should copy the buffer of bytearray into the myMailBoName. 如果需要数据,则应将字节数组的缓冲区复制到myMailBoName中。

use memcpy function 使用memcpy函数

试试这个代码片段

const char *myMailboxName = name.toLatin1().data();

Use strdup. 使用strdup。 It does the allocation and the copy at the same time. 它同时进行分配和复制。 Just remember to free it once you're done. 只要记住,一旦完成就将其释放。

You can really use strdup ( stackoverflow question about it ), as Mike recommends, but also you can do that: 正如Mike所建议的,您确实可以使用strdup有关它的stackoverflow问题 ),但是您也可以这样做:

// 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 . 到达那里: stackoverflow类似的问题

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... :) 至少这节省了一些输入... :)

consider following example 考虑下面的例子
QString str = "BlahBlah;"

try this 尝试这个
char* mychar = strdup(qPrintable(str));

or this 或这个
char* mychr = str.toStdString().c_str();

or this 或这个
char* mychar = strdup(str.ascii());

Every syntax worked for me ;) 每种语法都对我有用;)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM