【问题标题】:Is this reinterpret_cast between RECT and POINT array safe?RECT 和 POINT 数组之间的 reinterpret_cast 安全吗?
【发布时间】:2011-01-31 08:34:48
【问题描述】:

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;

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

void ThatFunction( POINT* points, int numberOfElements );

我们有以下代码:

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

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

这样的演员表安全吗?

【问题讨论】:

    标签: c++ windows winapi visual-c++ casting


    【解决方案1】:

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

    【讨论】:

    • +1 包装也是明确定义的,正是这种(非便携式)技巧使reinterpret_cast 安全。
    【解决方案2】:

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

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

    【讨论】:

      【解决方案3】:

      我认为它会按您期望的方式工作,但对我来说,安全并不是什么意思。

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

      【讨论】:

        猜你喜欢
        • 2013-04-22
        • 2010-09-29
        • 1970-01-01
        • 1970-01-01
        • 2021-11-23
        • 2018-08-23
        • 1970-01-01
        • 2019-07-20
        • 1970-01-01
        相关资源
        最近更新 更多