对HWND(VS8 C ++)很长
时间:2020-03-06 14:20:11 来源:igfitidea点击:
我如何才能长期投放到HWND(C ++ Visual Studio 8)?
Long lWindowHandler; HWND oHwnd = (HWND)lWindowHandler;
但是我收到以下警告:
warning C4312: 'type cast' : conversion from 'LONG' to 'HWND' of greater size
谢谢。
解决方案
只要我们确定自己拥有的LONG确实是HWND,就很简单:
HWND hWnd = (HWND)(LONG_PTR)lParam;
HWND是窗口的句柄。
在WinDef.h中声明此类型,如下所示:
typedef HANDLE HWND;
HANDLE是对象的句柄。
在WinNT.h中声明此类型,如下所示:
typedef PVOID HANDLE;
最后,PVOID是指向任何类型的指针。
在WinNT.h中声明此类型,如下所示:
typedef void *PVOID;
因此,HWND实际上是指向void的指针。我们可以像这样向HWND投个长字:
HWND h = (HWND)my_long_var;
但要非常小心my_long_var中存储了哪些信息。我们必须确保其中有一个指针。
以后编辑:
该警告表明我们已打开64位可移植性检查。如果我们要构建32位应用程序,则可以忽略它们。
仅当我们不在64位版本的Windows上运行时,这样做才是安全的。 LONG类型是32位,但是HANDLE类型可能是64位。我们需要将代码设置为64位干净。简而言之,我们将需要将LONG更改为LONG_PTR。
使用指针类型的规则:
Do not cast pointers to int, long, ULONG, or DWORD. If you must cast a pointer to test some bits, set or clear bits, or otherwise manipulate its contents, use the UINT_PTR or INT_PTR type. These types are integral types that scale to the size of a pointer for both 32- and 64-bit Windows (for example, ULONG for 32-bit Windows and _int64 for 64-bit Windows). For example, assume you are porting the following code: ImageBase = (PVOID)((ULONG)ImageBase | 1); As a part of the porting process, you would change the code as follows: ImageBase = (PVOID)((ULONG_PTR)ImageBase | 1); Use UINT_PTR and INT_PTR where appropriate (and if you are uncertain whether they are required, there is no harm in using them just in case). Do not cast your pointers to the types ULONG, LONG, INT, UINT, or DWORD. Note that HANDLE is defined as a void*, so typecasting a HANDLE value to a ULONG value to test, set, or clear the low-order 2 bits is an error on 64-bit Windows.