
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%明确定义的行为,但实际上它确实是安全的. (可以想象,一个积极的优化编译器可能会执行一些导致代码行为不当的转换,但是这样的优化会破坏很多现有代码,编译器实现者很有动力避免这种情况.)
总结以上是内存溢出为你收集整理的为什么不同结构指针之间的类型转换是可行的?全部内容,希望文章能够帮你解决为什么不同结构指针之间的类型转换是可行的?所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)