【发布时间】:2012-08-13 07:13:19
【问题描述】:
我正在编写一个使用 Win32 API 的库,我希望能够为 ASCII 和 Unicode 编译它(宽字符是 type),并且我正在生成一个内部类名(阅读:WinAPI “类”),我将一个整数附加到一个字符串中,以便为各种 Windows 函数创建唯一的类名。
所用变量的定义:
LPCTSTR lpszClassName; // This is char* if ASCII, wchar_t* if Unicode.
#ifdef UNICODE
std::wostringstream Convert;
#else
std::ostringstream Convert;
#endif
有问题的函数:
void Base::MakeClassName () {
#ifdef _DEBUG_
cerr << "Base::MakeClassName() called\n";
#endif
static int name_mod = 0;
name_mod++;
lpszClassName = TEXT("Win32WinNo");
Convert << lpszClassName << name_mod;
lpszClassName = Convert.str().c_str();
#ifdef _DEBUG_
cerr << "Generated class name = " << lpszClassName << "\n";
#endif
}
在 ASCII 中,我得到 Generated class name = Win32WinNo1
在 Unicode 中,我得到一个十六进制值。这向我表明宽字符 wostringstream 没有做我想要的。无论哪种方式,CreateWindow 似乎都不喜欢它(程序挂起,如果我调试它,它就会崩溃。)
我不是 100% 熟悉 stringstream,根据有限的文档,它返回一个“字符串”对象,但我需要一个指向 LPCTSTR 的 C 样式字符串的指针,因此,Convert.str().c_str()。我得到的东西不能正常工作,如果我在 RegisterClass 和 CreateWindow 调用中尝试 TEXT("Win32WinNo1") ,它可以工作,但是上面返回的字符串是垃圾。
我做错了什么?我也担心它是否没有将整数附加到字符串中。 wostringstream 是否将整数转换为 wchar_t?
【问题讨论】:
-
你可以通过定义
typedef std::basic_stringstream<TCHAR> tstringstream等来节省很多#ifdef的混乱。它只是不适用于std::cerr,因为这是一个对象,而不是一个类型。
标签: c++ winapi unicode ascii stringstream