tags:

views:

3354

answers:

3

Hi, How can I cast long to HWND (C++ visual studio 8)?

Long lWindowHandler;
HWND oHwnd = (HWND)lWindowHandler;

But I got the following warning:

warning C4312: 'type cast' : conversion from 'LONG' to 'HWND' of greater size

Thanks.

+1  A: 

As long as you're sure that the LONG you have is really an HWND, then it's as simple as:

HWND hWnd = (HWND)lParam;
Roger Lipscombe
Thanks for your reply.I tried that and got a warning:warning C4312: 'type cast' : conversion from 'LONG' to 'HWND' of greater sizeany suggestions?Thanks.
+1  A: 

HWND is a handle to a window. This type is declared in WinDef.h as follows:

typedef HANDLE HWND;

HANDLE is handle to an object. This type is declared in WinNT.h as follows:

typedef PVOID HANDLE;

Finally, PVOID is a pointer to any type. This type is declared in WinNT.h as follows:

typedef void *PVOID;

So, HWND is actually a pointer to void. You can cast a long to a HWND like this:

HWND h = (HWND)my_long_var;

but very careful of what information is stored in my_long_var. You have to make sure that you have a pointer in there.

Later edit: The warning suggest that you've got 64-bit portability checks turned on. If you're building a 32 bit application you can ignore them.

+4  A: 

Doing that is only safe if you are not running on a 64 bit version of windows. The LONG type is 32 bits, but the HANDLE type is probably 64 bits. You'll need to make your code 64 bit clean. In short, you will want to change the LONG to a LONG_PTR.

Rules for using pointer types:

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.

1800 INFORMATION