将 std::string 转换为 wchar_t* 的类型定义

Converting std::string to a typedef of wchar_t*

本文关键字:类型 定义 wchar std string 转换      更新时间:2023-10-16

我正在通过控制台从用户读取文件目录,我必须将值存储在pxcCHAR*变量中,这是 SDK 对wchar_t*typedef

我发现我可以通过执行以下操作将std::string转换为std::wstring

#include <iostream>
int main(){
std::string stringPath;
std::getline(std::cin, stringPath);
std::wstring wstrPath = std::wstring(stringPath.begin(), stringPath.end());
const wchar_t* wcharPath = wstrPath.c_str();
return 0;
}

运行此代码时,我通过调试看到这些值。

stringPath= "C:/Users/"
wstrPath= L"C:/Users/"
wcharPath= 0x00b20038 L"C:/Users/"

连接到wcharPath前面的值从何而来?

此外

因为pxcCHAR*wchar_t*typedef,所以我认为简单地这样做是可以的:

pxcCHAR* mFilePath = wcharPath;

但是,我收到一条消息,指出"const wchar_t*"不能用于初始化类型为"pxcCHAR*"的实体。

我期望隐式转换起作用,但事实并非如此。如何克服此错误?

使用std::wstring(stringPath.begin(), stringPath.end())是处理字符串转换的错误方法,除非您可以保证只处理 7 位 ASCII 数据(文件系统并非如此(。这种类型的转换根本不考虑字符编码。 将std::string转换为std::wstring的正确方法是使用std::wstring_convertMultiByteToWideChar()或其他等效项。 如果你环顾四周,有很多这样的例子。

最好一开始就使用std::wstring而不是std::string,例如:

#include <iostream>
#include <string>
int main(){
std::wstring stringPath;
std::getline(std::wcin, stringPath);
const wchar_t* wcharPath = stringPath.c_str();
return 0;
}

连接到wcharPath前面的值从何而来?

调试器。它只是向您显示指针指向的内存地址,然后是该地址的实际字符数据。

我收到一条消息,指出"const wchar_t*"不能用于初始化类型为"pxcCHAR*"的实体。

这意味着pxcCHAR不是const wchar_t的typedef,而更可能是本身wchar_t的typedef。无论使用何种类型,都不能将const指针分配给非const指针。 如果需要进行此类分配,则必须将const键入,例如使用const_cast

pxcCHAR* mFilePath = const_cast<wchar_t*>(wcharPath);

读取转换 Unicode 和 ANSI 字符串。您应该使用MultiByteToWideChar.

话虽如此,您不太可能需要这样做(并且很可能对于任何CP1252 的代码页,结果都是不正确的(。您可能必须在任何地方使用宽字符串。

哦,阅读 绝对最低限度 每个软件开发人员绝对,肯定必须了解 Unicode 和字符集(没有借口!