3

このコード スニペットは、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 行目でポインタ toxcb_generic_event_tをポインタ to に型キャストしていますがxcb_expose_event_t、標準 C 言語でこのような操作を行うのは良い方法でしょうか? また、その意味を教えてください。

4

2 に答える 2

2

C プログラミング言語から- 第 2 版

A.8.3 構造体と共用体の宣言

構造体へのポインターが最初のメンバーへのポインターの型にキャストされる場合、結果は最初のメンバーを参照します。

しかし、この場合xcb_expose_event_tは次のように定義されます。

typedef struct {
    uint8_t      response_type; /* The type of the event, here it is XCB_EXPOSE */
    uint8_t      pad0;
    uint16_t     sequence;
    xcb_window_t window;        /* The Id of the window that receives the event (in case */
                                /* our application registered for events on several windows */
    uint16_t     x;             /* The x coordinate of the top-left part of the window that needs to be redrawn */
    uint16_t     y;             /* The y coordinate of the top-left part of the window that needs to be redrawn */
    uint16_t     width;         /* The width of the part of the window that needs to be redrawn */
    uint16_t     height;        /* The height of the part of the window that needs to be redrawn */
    uint16_t     count;
} xcb_expose_event_t;

ご覧のとおり、 の最初のメンバーはstructとして定義されxcb_generic_event_tていません。未定義の動作のように思えます。

于 2014-10-03T17:09:01.373 に答える