这是RECT和POINT阵列之间的reinterpret_cast安全吗?

sha*_*oth 4 c++ windows winapi casting visual-c++

Windows SDK包含一组typedef:

typedef long LONG;

typedef struct tagPOINT
{
    LONG  x;
    LONG  y;
} POINT;

typedef struct tagRECT
{
    LONG    left;
    LONG    top;
    LONG    right;
    LONG    bottom;
} RECT;
Run Code Online (Sandbox Code Playgroud)

然后,有一个WinAPI函数,它需要一个指向POINT结构数组的指针和该数组的长度:

void ThatFunction( POINT* points, int numberOfElements );
Run Code Online (Sandbox Code Playgroud)

我们有以下代码:

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

因此RECT被视为两个POINT结构的数组.

这样的演员安全吗?

sel*_*bie 9

因为Windows开发人员在WinDef.h中使用相同的打包声明了RECT和POINT,所以你几乎可以认为它是安全的.Win32 API,MapWindowPoints,是一个可以传递RECT或一对POINT的函数的示例.文档甚至建议使用它.

  • +包装也是明确定义的,这是(非便携)技巧,使`reinterpret_cast`安全. (3认同)

MSa*_*ers 5

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

static_assert(sizeof(struct tagRECT) == 2 * sizeof(POINT));
static_assert(offsetof(struct tagRECT, right) == sizeof(POINT));
Run Code Online (Sandbox Code Playgroud)