Winapi 以TCHARs为单位的大小是sizeof还是tcslen?
msdn中以TCHAR表示的尺寸是什么意思 例如: lpFilename缓冲区的大小,以TCHARs为单位 如果我有缓冲区:Winapi 以TCHARs为单位的大小是sizeof还是tcslen?,winapi,Winapi,msdn中以TCHAR表示的尺寸是什么意思 例如: lpFilename缓冲区的大小,以TCHARs为单位 如果我有缓冲区: WCHAR buf[256]; 所以我需要通过256,还是512_tsclen(buf)或sizeof(buf)?sizeof总是在chars中,这相当于说它总是以字节为单位TCHARs不一定是chars,因此sizeof是错误的答案 如果要传递缓冲区中字符串的长度(在TCHARs中),则使用tsclen(buf)是正确的。如果要传递缓冲区本身的长度,可以使用sizeo
WCHAR buf[256];
所以我需要通过256,还是512_tsclen(buf)或sizeof(buf)?
sizeof
总是在char
s中,这相当于说它总是以字节为单位TCHAR
s不一定是chars
,因此sizeof
是错误的答案
如果要传递缓冲区中字符串的长度(在TCHAR
s中),则使用tsclen(buf)
是正确的。如果要传递缓冲区本身的长度,可以使用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.
}
256,_tsclen(buf),或者可以说sizeof(buf)/sizeof(TCHAR)这是一种情况,其中很有帮助。大多数Windows API调用使用
cch
前缀指定字符计数,而cb
前缀用于字节计数。“大小[…]以TCHARs为单位”与字符数相同。换句话说:使用\u tcslen
。再次阅读我的问题。如果我想通过长度,你是说tsclen(buf)。我在问:我需要传递什么:一段字符串,或者一段buf。那么我需要做什么:tsclen(buf)或sizeof(buf)/sizeof(buf[0]),如果它需要“lpFilename缓冲区的大小,以TCHARs为单位。”???这是一个很好的答案,Adrian不需要再次阅读这个问题。还有\u countof
-我不确定这和数组化@HarryJohnston之间的区别是什么:我相信唯一的区别是,它们在非数组的对象上使用时会产生不同的错误消息。这是C++的。编译C代码时,它们的实现是相同的。