Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is this reinterpret_cast between RECT and POINT array safe?

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's a WinAPI function that expects a pointer to an array of POINT structs and the length of that 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 that RECT is being treated as an array of two POINT structures.

Is such cast safe?

like image 464
sharptooth Avatar asked Dec 03 '22 03:12

sharptooth


1 Answers

Because the Windows developers declared RECT and POINT right next to each in WinDef.h with the same packing, you can pretty much assume that it is safe. The Win32 API, MapWindowPoints, is an example of a function that can be be passed a RECT or a pair of POINTs. The docs even suggest using it as such.

like image 112
selbie Avatar answered Dec 04 '22 18:12

selbie