c++ - 如何在 Windows 上将 Qt QString 转换为 LPCTSTR
问题描述
我试图打开注册表并修改它。这是我打开注册表的方式:
HKEY hKey;
LPCTSTR subKey = TEXT("a registry subkey to be opened");
RegOpenKeyEx(HKEY_LOCAL_MACHINE, subKey, 0, KEY_ALL_ACCESS , &hKey);
但是这里有一个问题,我想用aQString
来务实地改变子键。并把QString
这样的:
QString subKeyString = QString("%1").arg(subKeyName);
LPCTSTR subKey = TEXT(subKeyString); //but it's not working here
我认为这是因为我没有更改QString
to LPCTSTR
,我尝试了这个解决方案,但我仍然无法找到将自定义QString
放入TEXT
宏的方法。我不太确定引擎盖下的 WinApi,我只是尝试了我可能做的事情。
有没有办法解决这个问题?
编辑:
这是我转换QString
为LPCTSTR
:
QString testString = "converting QString to LPCSTR";
QByteArray testStringArr = testString.toLocal8Bit();
LPCSTR lp = LPCSTR(testStringArr.constData()); //the QString is converted to LPCTSTR
//but when I put the LPCSTR to the TEXT macro, the error is still there, like the next line below will not complie
LPCSTR lp = TEXT(LPCSTR(testStringArr.constData())); //This line will not work
解决方案
该TEXT()
宏仅适用于编译时文字,不适用于运行时数据。 TCHAR
和相关的 API 旨在帮助人们将他们的代码从基于 ANSI 的 Win9x/ME 迁移到基于 Unicode 的 WinNT 4+,通过在 和 之间映射文字char
,以及在和变体wchar_t
之间映射函数名称。但那些日子早已一去不复返了。A
W
在这种情况下,正确的解决方案是完全忽略TCHAR
并只关注 Unicode。AQString
是 Unicode 字符串的包装器。因此,仅使用基于 Unicode 的 Registry API 函数并假装TCHAR
不存在。
在 Windows 上,基于 Unicode 的 API 需要 UTF-16 编码的wchar_t
字符串。使用该QString::toStdWString()
方法获取 a std::wstring
,它是一个wchar_t
字符串的 C++ 包装器:
QString subKeyString = QString("%1").arg(subKeyName);
std::wstring subKey = subKeyString.toStdWString();
HKEY hKey;
RegOpenKeyExW(HKEY_LOCAL_MACHINE, subKey.c_str(), 0, KEY_ALL_ACCESS, &hKey);
或者,您可以使用该QString::utf16()
方法。但是,它返回一个const ushort*
指针,因此您必须将其类型转换为const wchar_t*
:
QString subKeyString = QString("%1").arg(subKeyName);
LPCWSTR subKey = reinterpret_cast<LPCWSTR>(subKeyString.utf16());
HKEY hKey;
RegOpenKeyExW(HKEY_LOCAL_MACHINE, subKey, 0, KEY_ALL_ACCESS, &hKey);
推荐阅读
- mysql - 如何获得 n SELECTS 的交集?
- vue.js - 使用Vue js动态路由匹配从一个配置文件/:id到另一个问题
- css - 如何修复 Slick.js 中的第一张幻灯片并从第二张幻灯片开始?
- java - 使用 Spring 反应式数据自动配置连接到 AWS 键空间
- spring-boot - Kotlin Spring Boot Dependency Injection
- typescript - What is the idiomatic way in TypeScript to extend an object (already implementing an interface) to a wider interface?
- java - Spring Webflux 如何在不阻塞的情况下顺序调用 2 个不同的服务?
- swift - Equivalent of a popover in SpriteKit
- php - Apache 2.4, PHP 7.4.7, Windows 10 can't load cURL Extension from Apache Service but loads fine from Command Line with httpd
- node.js - 404 error when connecting to IP address but not in domain name