来自msdn的TCHAR中的大小是什么意思?
例如:
lpFilename缓冲区的大小,以TCHAR为单位。
如果我有缓冲区:
WCHAR buf[256];
所以我需要传递256或512? _tsclen(buf)或sizeof(buf)?
答案 0 :(得分:3)
sizeof
始终位于char
中,这相当于说它总是以字节为单位。 TCHAR
不一定是chars
,因此sizeof
是错误的答案。
使用tsclen(buf)
是正确的如果您希望传递缓冲区中字符串的长度(在TCHAR
s中)。如果要传递缓冲区本身的长度,可以使用sizeof(buf)/sizeof(TCHAR)
或更一般地sizeof(buf)/sizeof(buf[0])
。 Windows提供了一个名为ARRAYSIZE
的宏,以避免输入这个常见的习惯用法。
但是只有当buf
实际上是缓冲区而不是指向缓冲区的指针时才能这样做(否则sizeof(buf)
会给你一个指针的大小,这是不是你需要的。)
一些例子:
TCHAR buffer[MAX_PATH];
::GetWindowsDirectory(buffer, sizeof(buffer)/sizeof(buffer[0])); // OK
::GetWindowsDirectory(buffer, ARRAYSIZE(buffer)); // OK
::GetWindowsDirectory(buffer, _tcslen(buffer)); // Wrong!
::GetWindowsDirectory(buffer, sizeof(buffer)); // Wrong!
TCHAR message[64] = "Hello World!";
::TextOut(hdc, x, y, message, _tcslen(message)); // OK
::TextOut(hdc, x, y, message, sizeof(message)); // Wrong!
::TextOut(hdc, x, y, message, -1); // OK, uses feature of TextOut
void MyFunction(TCHAR *buffer) {
// This is wrong because buffer is just a pointer to the buffer, so
// sizeof(buffer) gives the size of a pointer, not the size of the buffer.
::GetWindowsDirectory(buffer, sizeof(buffer)/sizeof(buffer[0])); // Wrong!
// This is wrong because ARRAYSIZE (essentially) does what we wrote out
// in the previous example.
::GetWindowsDirectory(buffer, ARRAYSIZE(buffer)); // Wrong!
// There's no right way to do it here. You need the caller to pass in the
// size of the buffer along with the pointer. Otherwise, you don't know
// how big it actually is.
}