#language jp ''このページはWritingPortableDriversセクションの一部です。''<
> == データアラインメント == 原文: [[http://kernelnewbies.org/DataAlignment|DataAlignment]] gccコンパイラは通常、実行速度を速くさせるために、構造体の個々のフィールドをバイト境界に合わせます。 例として、次のコードとその実行結果を見てください。 {{{ #!cplusplus #include #include struct foo { char a; short b; int c; }; #define OFFSET_A offsetof(struct foo, a) #define OFFSET_B offsetof(struct foo, b) #define OFFSET_C offsetof(struct foo, c) int main () { printf ("offset A = %d\n", OFFSET_A); printf ("offset B = %d\n", OFFSET_B); printf ("offset C = %d\n", OFFSET_C); return 0; } }}} 上記のプログラムを実行すると、次のように出力します。 {{{ offset A = 0 offset B = 2 offset C = 4 }}} この出力は、コンパイラが構造体{{{struct foo}}}のフィールド{{{b}}}と{{{c}}}を偶数バイト境界に合わせた ことを示しています。これは構造体のデータをメモリ上にオーバーレイするときに問題となります。一般的に、 ドライバで使用されているデータ構造は、個々のフィールドが偶数バイトとなるようにパディングしません。 そのため、gccの属性{{{(packed)}}}を使用し、構造体の中に「メモリホール」を作らないようにコンパイラに 指示します。 次に示すように、構造体struct fooに対してpacked属性を使用するように修正した場合、 {{{ #!cplusplus struct foo { char a; short b; int c; } __attribute__((packed)); }}} プログラムの出力は次のように変わります。 {{{ offset A = 0 offset B = 1 offset C = 3 }}} これで構造体の中にメモリホールはなくなりました。 このpacked属性は、前述の構造体で使用したように構造体全体をパックするために使用することもできますし、 構造体の中の特定のいくつかのフィールドだけをパックすることにも使用できます。 たとえば、struct usb_ctrlrequestはinclude/usb.hの中で次のように定義されています。 {{{ #!cplusplus struct usb_ctrlrequest { __u8 bRequestType; __u8 bRequest; __le16 wValue; __le16 wIndex; __le16 wLength; } __attribute__ ((packed)); }}} このデータ構造は、構造体全体がパックされることを保証しているので、データを直接USBコネクションに 書き込むことができます。 しかし、次に示すstruct usb_endpoint_descriptorの定義は次のようになっています。 {{{ #!cplusplus struct usb_endpoint_descriptor { __u8 bLength __attribute__((packed)); __u8 bDescriptorType __attribute__((packed)); __u8 bEndpointAddress __attribute__((packed)); __u8 bmAttributes __attribute__((packed)); __le16 wMaxPacketSize __attribute__((packed)); __u8 bInterval __attribute__((packed)); __u8 bRefresh __attribute__((packed)); __u8 bSynchAddress __attribute__((packed)); unsigned char *extra; /* Extra descriptors */ int extralen; }; }}} このデータ構造は、構造体の最初の部分はパックされていて、USBコネクションから直接データを読み込むのに 使用できますが、extraフィールドとextralenフィールドは高速にアクセスできるように、コンパイラがバイト境界を 合わせることがあります。