加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

为什么不同结构指针之间的类型转换是可行的?

发布时间:2020-12-16 09:54:36 所属栏目:百科 来源:网络整理
导读:此代码段从 last tutorial example of the events in XCB复制: 01 xcb_generic_event_t *event;02 while ( (event = xcb_wait_for_event (connection)) ) {03 switch (event-response_type ~0x80) {04 case XCB_EXPOSE: {05 xcb_expose_event_t *expose = (
此代码段从 last tutorial example of the events in XCB复制:

01    xcb_generic_event_t *event;
02    while ( (event = xcb_wait_for_event (connection)) ) {
03        switch (event->response_type & ~0x80) {
04        case XCB_EXPOSE: {
05            xcb_expose_event_t *expose = (xcb_expose_event_t *)event;
06            printf ("Window %"PRIu32" exposed. Region to be redrawn at location (%"PRIu16",%"PRIu16"),with dimension (%"PRIu16",%"PRIu16")n",07                    expose->window,expose->x,expose->y,expose->width,expose->height );
08            break;
09        }

在第5行,指向xcb_generic_event_t的指针是指向xcb_expose_event_t的指针,这是用标准C语言进行这种操作的好方法吗?请解释一下它的含义是什么?

解决方法

这是可行的,因为两个结构都以相同的几个成员开始.

我没有使用过xcb,但只是看一下使用它的代码我假设xcb_wait_for_event()返回一个指向xcb_generic_event_t对象的指针,在这种情况下返回一个实际指向xcb_expose_event_t事件的指针.顾名思义,前者是一种“通用”类型,可用作几种更具体类型的占位符.前几个成员(包括response_type成员)是共享的,因为它们具有相同的大小并且在两种结构类型中存储在相同的偏移量中.因此,代码可以安全地引用xcb_generic_event_t对象的response_type成员,并基于该推断该对象实际上是xcb_expose_event_t对象.指针转换允许代码将对象重新解释为xcb_expose_event_t对象.

查看两种类型的链接定义,我看到xcb_generic_event_t实际上有5个成员,只有前3个与xcb_expose_event_t共享.只要代码不引用xcb_generic_event_t的最后2个成员,这就不太可能导致问题.

C标准作为特殊保证涵盖了这种情况.引用N1570 6.5.3.2,第6段:

One special guarantee is made in order to simplify the use of unions:
if a union contains several structures that share a common initial
sequence (see below),and if the union object currently contains one
of these structures,it is permitted to inspect the common initial
part of any of them anywhere that a declaration of the completed type
of the union is visible. Two structures share a common initial
sequence
if corresponding members have compatible types (and,for
bit-fields,the same widths) for a sequence of one or more initial
members.

严格地说,这仅适用于两个结构是联合的成员.但是,C编译器满足此保证的最简单方法是为所有具有共同初始子序列的结构提供与该子序列相同的布局.如果问题中的代码可能没有100%明确定义的行为,但实际上它确实是安全的. (可以想象,一个积极的优化编译器可能会执行一些导致代码行为不当的转换,但是这样的优化会破坏很多现有代码,编译器实现者很有动力避免这种情况.)

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读