简体   繁体   English

如何将QString转换为LPCSTR(Unicode)

[英]How to convert QString to LPCSTR (Unicode)

how can I convert QString to LPCSTR ? 如何将QString转换为LPCSTR?

How do I do it when #ifdef UNICODE is defined and when it isn't ? 定义#ifdef UNICODE时(未定义)如何处理?

Thanks very much :) 非常感谢 :)

I guess: 我猜:

QString str("ddddd");
LPCSTR lstr = str.toStdString().c_str();

QString can always hold Unicode; QString可以始终保留Unicode; LPCSTR is never Unicode. LPCSTR绝不是Unicode。 This means that you do have to consider what to do with the characters that won't fit. 这意味着您必须考虑如何处理不合适的字符。 This isn't a "which method to use" question, but a design question. 这不是一个“使用哪种方法”的问题,而是一个设计问题。

It's quite possible that in your specific case, you absolutely know that the QString only contaisn characters from your local "ANSI" codepage (also known as ACP ). 在您的特定情况下,您很有可能完全知道QString仅包含本地“ ANSI”代码页(也称为ACP )中的字符。 In that case, the correct function is QString::toLocal8Bit () . 在这种情况下,正确的函数是QString::toLocal8Bit ()

Alternatively, you might know that the QString only contains characters from Latin1 (ISO 8859-1). 另外,您可能知道QString仅包含Latin1(ISO 8859-1)中的字符。 In that case, the correct function is QString::toLatin1() . 在这种情况下,正确的函数是QString::toLatin1()

You could try to call QString::toUtf8() . 您可以尝试调用QString::toUtf8() This will always produce a valid byte array, even if the QString contained all Unicode characters. 即使QString包含所有Unicode字符,这也将始终产生有效的字节数组。 However, formally you can't point a LPCSTR to it: UTF-8 is not a valid ACP codepage. 但是,形式上您不能指向LPCSTR :UTF-8不是有效的ACP代码页。 And presumably, you want this LPCSTR to pass to another function outside your control. 并且大概是您希望此LPCSTR传递到您控制范围之外的另一个函数。 It's likely that function won't expect UTF-8. 该功能可能不会使用UTF-8。 If it expected Unicode at all, it would take a LPCWSTR . 如果完全希望使用Unicode,则需要使用LPCWSTR

I found following solution from here and it works flawlessly for me: 我从这里找到以下解决方案,它对我而言毫无瑕疵:

void fooSub(LPSTSTR X); // this is our function :-)

foo()
{
    QString text;
    if(sizeof(TCHAR) == 1)
        fooSub((LPCSTR)text.toLocal8Bit().constData()); // here you have to check, how to convert, you could also use utf8(), ...
    else
        fooSub((LPCWSTR)text.utf16());
}
LPCSTR == const char *

it's not unicode, then 那不是unicode,那么

LPCSTR s = (const char *)qtString; LPCSTR s =(const char *)qtString;

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

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