Is this reinterpret_cast between RECT and POINT array safe?

The Windows SDK contains a set of typedefs:

typedef long LONG; typedef struct tagPOINT { LONG x; LONG y; } POINT; typedef struct tagRECT { LONG left; LONG top; LONG right; LONG bottom; } RECT; 

then there is a WinAPI function that expects a pointer to an array of POINT structures and the length of this array:

 void ThatFunction( POINT* points, int numberOfElements ); 

and we have the following code:

 RECT rect = ...//obtained from somewhere ThatFunction( reinterpret_cast<POINT*>( &rect ), 2 ); 

so RECT considered as an array of two POINT structures.

Is such a cast safe?

+4
source share
3 answers

For this particular Win32 structure, yes. You must, of course, make this assumption explicit:

 static_assert(sizeof(struct tagRECT) == 2 * sizeof(POINT)); static_assert(offsetof(struct tagRECT, right) == sizeof(POINT)); 
+5
source

Since Windows developers declared RECT and POINT right next to everyone in WinDef.h with the same packaging, you can safely assume that it is safe. The Win32 API, MapWindowPoints , is an example of a function to which a RECT or a pair of POINTs can be passed. Documents even suggest using it as such.

+9
source

I think it will work as you expect, but for me it is not safe.

If you really want to play it safe, it's best to create a whole new POINT object and set x and y respectively to the RECT left and top fields.

+4
source

Source: https://habr.com/ru/post/1337739/


All Articles