VC++编译器无法捕获 HANDLE 和 PHANDLE 类型不匹配
我花了一整天的时间寻找由于错误地将 Windows PHANDLE 类型传递给需要 HANDLE 的函数而导致的错误!我期望 VC++ 2010 编译器能够捕获如此简单且明显的类型不匹配错误。然而,事实并非如此。但事实并非如此。
仔细一看,HANDLE 在 winnt.h 中被定义为 void 指针,因此 PHANDLE 只是 void 指针。由于任何内容都可以传递给 void * 或 void **,因此编译器不会警告 PHANDLE 和 HANDLE 不匹配。
有没有办法避免这样的问题。我不知道有多少其他 Windows 类型被类型定义为 void *。有什么策略可以避免此类错误吗?
例如,以下代码在 VC++ 2010 中编译没有任何错误,尽管该函数是由错误的指针类型调用的。而且,除非知道 HANDLE(或任何其他 Windows 类型)是一个 void 指针,否则陷阱的存在并不明显:
void f1 (HANDLE h) {
printf("%x",h);
}
int _tmain(int argc, _TCHAR* argv[])
{
PHANDLE ph=NULL;
int c=0;
f1(ph);
f1(&c);
return 0;
}
I spent a whole day looking for a bug caused by wrongly passing Windows PHANDLE type to a function expecting HANDLE!!! I was expecting the VC++ 2010 compiler to catch such a simple and obvious type mismatch error. However, it didn't. It just didn't.
On a closer look, HANDLE is defined as void pointer in winnt.h and so PHANDLE is just void pointer pointer. Since anything can be passed to void * or void ** so PHANDLE and HANDLE mismatch can't be warned by the compiler.
Is there anyway to avoid such a problem. I don't know how many other Windows types are typedef'ed as void *. Are there any strategies to avoid such errors?
For example, the following compiled without any error in VC++ 2010, although the function is called by wrong pointer types. And, it is not obvious the pitfall is there unless one knows HANDLE (or any other Windows types) is a void pointer:
void f1 (HANDLE h) {
printf("%x",h);
}
int _tmain(int argc, _TCHAR* argv[])
{
PHANDLE ph=NULL;
int c=0;
f1(ph);
f1(&c);
return 0;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
可以将
HANDLE
视为所有句柄的基类型,例如HWND
、HDC
等。因为C不支持基本类型的概念,他们必须将其设为void*
。在大多数情况下,您的应用程序应使用
STRICT
标志集进行编译。这将确保所有特定句柄实际上都基于结构,因此您不会遇到任何问题。但是,如果您确实编写了一个与通用HANDLE
一起使用的方法,那么您就必须小心了!The way to think of
HANDLE
is as the base type for all handles, such asHWND
,HDC
etc. Because C doesn't support the concept of a base type they had to make it avoid*
.In most cases your app should be compiled with the
STRICT
flag set. This will ensure that all specific handles are actually based off of structures and so you won't have any issues. However, if you do write a method that works with a generalHANDLE
then you're going to have to be careful!