RECT和POINT数组之间的reinterpret_cast是否安全?

Windows SDK包含一组typedefs:

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

那么就有一个WinAPI函数需要指向一个POINT结构数组的指针和该数组的长度:

 void ThatFunction( POINT* points, int numberOfElements ); 

我们有以下代码:

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

所以RECT被视为两个POINT结构的数组。

这样的投射是否安全?

对于这个特定的Win32结构,是的。 你当然应该明确这个假设:

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

因为Windows开发人员在WinDef.h中的每个对象旁边都用相同的包装声明了RECT和POINT,所以可以认为它是安全的。 Win32 API, MapWindowPoints是一个可以传递RECT或一对POINT的函数的例子。 文档甚至建议使用它。

我认为它会以你期望的方式工作,但这对我来说不是安全的手段。

如果你真的想玩的安全,最好的办法是创建一个全新的POINT对象,并相应地使用RECT的lefttop字段设置xy