gpt4 book ai didi

c++ - 简单函数的 Unicode 编译器错误

转载 作者:行者123 更新时间:2023-11-30 00:40:17 25 4
gpt4 key购买 nike

感叹

我正在使用 Microsoft Visual Express C++ IDE。我最近从 DevC++ 过渡到了这个 IDE。

我有一个函数可以在 DevC++ 中完美运行,但在 MSVC++ 中它无法编译,因为 Unicode(我认为?)。我需要更改什么才能编译我的函数?

查看我得到的编译器错误的注释代码行

map <string, string> GetEvironmentVariablesEx()
{
map <string, string> envVariables;
char* environVar = GetEnvironmentStrings(); // Compile error: error C2440: 'initializing' : cannot convert from 'LPWCH' to 'char *'
char* pos = strchr( environVar, '\0' );

// Skip over the "=::=::\0" of the environVar string
if ( pos != NULL ) { environVar = ++pos; pos = strchr( environVar, '\0' ); }
else return envVariables;

while ( true )
{
char* delim = strchr( environVar, '=' );
if ( delim == NULL )
break;

string variable = string( environVar, strlen(environVar)-strlen(delim) );
string value = string( ++delim );

envVariables.insert( pair<string, string>(variable, value) );
environVar = ++pos;

// find the "\0\0" that identifies the end of environVar
if ( pos != NULL && *pos == 0 ) { break; }

pos = strchr( environVar, '\0' );
}

FreeEnvironmentStrings( environVar );
return envVariables;
}

PS:因为这个应用程序是用 Unicode 编译的,这是否意味着它可以在 ANSII 计算机和 UNICODE 计算机上运行 - 所以我的应用程序可以在国际上运行?

最佳答案

Visual C++ 正在尝试编译您的程序以支持 Unicode。在引擎盖下,这是通过 #define-ing UNICODE_UNICODE 宏完成的。这反过来又会导致您的程序使用 Win32 函数的 Unicode 变体。

每个 Win32 函数(接受或返回字符串)都有两个变体。例如,GetEnvironmentStrings 实际上是两个函数:GetEnvironmentStringsAGetEnvironmentStringsWGetEnvironmentStrings 解析为其中之一,具体取决于是否定义了 UNICODE 宏。

因此,您的程序正在为 Unicode 编译,编译器无法弄清楚如何获取 (Unicode) GetEnvironmentStringsW 的结果(这是一个 LPWCH - - 实际上 WCHAR *) 并将其放入 (ANSI) std::string

您可以执行以下一项(或多项)操作:

  1. 将您的整个程序转换为 Unicode(开始使用 std::wstring)。
  2. 明确使用 GetEnvironmentStringsA
  3. 改为针对非 Unicode 重新编译。
  4. 利用 Windows 中的 TCHAR 支持。你需要 define a tstring type .

这不是一个详尽的 list 。

回复:

Because this application is compiled in Unicode, does that mean that it will work on both ANSII computers & UNICODE computers - so my app will able to be run internationally?

计算机不是 ANSI 或 Unicode。操作系统是。上一个不支持 Unicode 的 Windows 版本是 Windows 3.11 for Workgroups。

也就是说,仅针对 Unicode 进行编译并不能使您的应用程序能够在国际上运行。它会工作得很好,但 Unicode 只涵盖字符集。您仍然需要担心翻译、日期和时间格式、数字格式、不同的日历。国际化、本地化和全局化不仅仅是启用 Unicode 支持。

关于c++ - 简单函数的 Unicode 编译器错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6401036/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com