Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assigning an arbitrary address to a HWND

As I understand from the MSDN documentation on Windows Data Types, a HWND is equivalent to a void*:

HWND - A handle to a window. This type is declared in WinDef.h as follows: typedef HANDLE HWND; HANDLE - A handle to an object. This type is declared in WinNT.h as follows: typedef PVOID HANDLE; PVOID - A pointer to any type. This type is declared in WinNT.h as follows: typedef void *PVOID;

However, if I try the following:

int foo;
HWND bar = &foo;

My compiler (VS2012) complains:

error C2440: '=' : cannot convert from 'int *' to 'HWND'
Types pointed to are unrelated; conversion requires reinterpret_cast,
C-style cast or function-style cast

I can't figure out the reason why. I've established that it's not related to the use of typedefs since the following compiles fine:

typedef void* MyType;
int foo;
MyType bar = &foo;

What is preventing me from assigning the address of an arbitrary object to a HWND?

The reason I want to do this, in case anyone objects to me trying to do it in the first place, is that I have some code involving HWNDs that I would like to unit test by supplying the HWNDs with known values that I can test for.

like image 217
JBentley Avatar asked Jan 15 '23 12:01

JBentley


1 Answers

If STRICT is defined during the compile, an HWND is defined as a pointer to a dummy struct instead of a void*.

One of the reasons that STRICT was added was to enable the compiler to catch the kind of implicit conversions that you want to do (and many people really didn't). Since you actually want the 'loose checking', make sure that STRICT isn't defined.

Or just cast.

(Note that the comments by yic81 on the MSDN documentation page you link to indicate that it's in need of some updating)

like image 144
Michael Burr Avatar answered Feb 01 '23 12:02

Michael Burr