windows 如何将 QString 转换为 LPCSTR (Unicode)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5443479/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-15 16:30:27  来源:igfitidea点击:

How to convert QString to LPCSTR (Unicode)

c++windowsqtqt4lpcstr

提问by MSalters

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 :)

非常感谢 :)

回答by snoofkin

I guess:

我猜:

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

回答by MSalters

QStringcan always hold Unicode; LPCSTRis never 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.

QString可以一直保持Unicode;LPCSTR从来都不是 Unicode。这意味着您必须考虑如何处理不适合的角色。这不是“使用哪种方法”的问题,而是设计问题。

It's quite possible that in your specific case, you absolutely know that the QStringonly contaisn characters from your local "ANSI" codepage (also known as ACP). In that case, the correct function is QString::toLocal8Bit ().

在您的特定情况下,您很可能完全知道QString本地“ANSI”代码页(也称为ACP)中唯一包含的字符。在这种情况下,正确的函数是QString::toLocal8Bit ()

Alternatively, you might know that the QStringonly contains characters from Latin1 (ISO 8859-1). In that case, the correct function is QString::toLatin1().

或者,您可能知道QString唯一包含来自 Latin1 (ISO 8859-1) 的字符。在这种情况下,正确的函数是QString::toLatin1()

You could try to call QString::toUtf8(). This will always produce a valid byte array, even if the QStringcontained all Unicode characters. However, formally you can't point a LPCSTRto it: UTF-8 is not a valid ACPcodepage. And presumably, you want this LPCSTRto pass to another function outside your control. It's likely that function won't expect UTF-8. If it expected Unicode at all, it would take a LPCWSTR.

你可以试试打电话QString::toUtf8()。这将始终产生一个有效的字节数组,即使QString包含所有 Unicode 字符。但是,正式地您不能指向LPCSTR它:UTF-8 不是有效的ACP代码页。据推测,您希望将LPCSTR其传递给您无法控制的另一个函数。该函数很可能不需要 UTF-8。如果它完全期望 Unicode,则需要一个LPCWSTR.

回答by zeFree

I found following solution from hereand 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());
}

回答by Mark.Ablov

LPCSTR == const char *

it's not unicode, then

那不是unicode

LPCSTR s = (const char *)qtString;

LPCSTR s = (const char *)qtString;