2010-07-13 96 views
3

我正在做一些win32字符串API调用,并假设字符串以宽字符串出现,这在XP和更新的版本中是有效的。我怎么能断言这一点?这是运行时检查还是编译时检查?在运行时,我怎么知道我是否在WinXP +上? win32

我做错了吗?这里有一个例子:

typedef std::basic_string<TCHAR> TString; 
inline TString queryRegStringValue(HKEY key, const TString& subkey, 
     const TString defaultValue = TEXT("")) 
{ 
    std::vector<char> out_bytes(256); 
    DWORD num_bytes = out_bytes.size(); 
    DWORD out_type; 
    long retval = RegQueryValueEx(key, subkey.c_str(), 0, &out_type, 
     reinterpret_cast<BYTE*>(&out_bytes[0]), &num_bytes); //comes out as a platform string. wide on XP 
    if (retval != 0) 
     return defaultValue; 
    if (num_bytes > 0) 
    { 
     assert(out_type == REG_SZ); 
     BOOST_STATIC_ASSERT(sizeof(TCHAR)==2); //what if someone runs my code on an older system? 
     return TString(reinterpret_cast<wchar_t*>(&out_bytes[0]), num_bytes/2); //assumes windows XP (wide string) 
    } 

    return TEXT(""); 
} 
+0

我错过了什么吗?根据msdn,RegQueryValueEx已经出现在Win2000中,它也完全支持unicode。 – 2010-07-13 19:41:01

回答

4

这是一个不是问题的问题。早在XP发布之前,Windows在过去的17年中一直是原生的Unicode操作系统。 David Cutler的大脑孩子NT 3.1从第一天开始就是Unicode。

如果您的程序出现在Window 9x计算机上,但仍然存在API层,可以将UTF-16字符串转换为8位字符。使用TCHAR进行新代码开发没有任何意义。

+0

我正在修改其他人广泛使用TCHAR的代码。在我的代码中使用std :: wstring是更好的形式吗? wstring应该相当于在widechar平台上的TString,所以我没有看到问题。 – 2010-07-13 20:33:43

+0

我不知道“TString”可能是什么。另一个宏?在一个传统的源代码文件中混合字符串typedefs不可能赢得任何朋友。 – 2010-07-13 20:46:20

+0

我打开了一个新的问题:http://stackoverflow.com/questions/3241645/proper-style-for-interfacing-with-legacy-tchar-code – 2010-07-13 21:21:57

1

我认为,这是怎么回事,就是当我编译,我编译反对统一的Windows API,所以如果我在非widechar窗口中运行我的可执行文件,它将无法运行。因此运行时检查是无用的。

如果我们在非widechar平台上编译(XP之前,或2000之前,或其他任何版本)编译将失败,我添加了编译时断言来强制生成错误。如果断言不存在,它将会失败,但更加隐秘。

相关问题