C USB驱动程序实现的联合与结构

C USB驱动程序实现的联合与结构,c,C,我正在尝试使用PIC32mx系列为打印机设备创建主机usb驱动程序。 我正在使用Microchip Library应用程序示例。 其中iI看到为了发送BDT,使用了下面提到的结构。 现在BDT应该是应用说明中记录的全部8个字节, 但是当我检查BD_ENTRY union变量的大小时,我发现它是不同的-12字节。如果我是对的,它应该是8字节。 我尝试使用Mikroc编译同一代码的这一特定部分,并使用proteus进行模拟,我发现字节长度(sizeof)为8字节 我有点困惑,而且我对指针、结构和联合

我正在尝试使用PIC32mx系列为打印机设备创建主机usb驱动程序。 我正在使用Microchip Library应用程序示例。 其中iI看到为了发送BDT,使用了下面提到的结构。 现在BDT应该是应用说明中记录的全部8个字节, 但是当我检查BD_ENTRY union变量的大小时,我发现它是不同的-12字节。如果我是对的,它应该是8字节。 我尝试使用Mikroc编译同一代码的这一特定部分,并使用proteus进行模拟,我发现字节长度(sizeof)为8字节

我有点困惑,而且我对指针、结构和联合的世界是新的

typedef union _BD_STAT {
    BYTE Val;
    struct {
        //If the CPU owns the buffer then these are the values
        unsigned BC8:1;         //bit 8 of the byte count
        unsigned BC9:1;         //bit 9 of the byte count
        unsigned BSTALL:1;      //Buffer Stall Enable
        unsigned DTSEN:1;       //Data Toggle Synch Enable
        unsigned INCDIS:1;      //Address Increment Disable
        unsigned KEN:1;         //BD Keep Enable
        unsigned DTS:1;         //Data Toggle Synch Value
        unsigned UOWN:1;        //USB Ownership
    };

    struct {
        //if the USB module owns the buffer then these are
        // the values
        unsigned :2;
        unsigned PID0:1;        //Packet Identifier
        unsigned PID1:1;
        unsigned PID2:1;
        unsigned PID3:1;
        unsigned :1;
    };

    struct {
        unsigned :2;
        unsigned PID:4;         //Packet Identifier
        unsigned :2;
    };
} BD_STAT;    

typedef union __attribute__ ((packed))__BDT {
    //typedef union __BDT{
    struct __attribute__ ((packed)) {
        //struct   
        BD_STAT     STAT;
        WORD        CNT:10;
        WORD        ADR;                      
        WORD        ADRH;                   
    };
    struct __attribute__ ((packed)) {
        //struct   
        DWORD       res  :16;
        DWORD       count:10;
    };

    DWORD           w[2];
    WORD            v[4];
    QWORD           Val;
} BDT_ENTRY;

为所有这些匿名结构命名(暂时),以便使用
sizeof
检查它们。我看到的关于位字段的一个问题是,一些编译器(包括gcc,至少有一次它对我有影响)受到位字段基类型的过度影响。因此,那些与
BD_STAT
中的
Byte
联合的
无符号位:1
位域可能会从4字节
无符号
中切掉它们的位,导致
BD_STAT
太大。如果使用
sizeof
验证,请尝试将基类型更改为
Byte
,并查看它是否打包得更小。

BD_STAT
中,使用
无符号字符
而不是
无符号

位字段始终具有基础类型的大小,而不是其大小之和。因此,
BD\u STAT
的长度是4字节。

结构填充会让你很困惑,所以最好删除它。我原以为你会得到16字节作为BDT\u条目的大小。一个字中有多少字节,DWORD和QWORD?我检查了QWORD大小如果是8个字节,我还通过删除-attrib和packed things来检查。。但是他们应该删除填充,可能是因为我使用的是免费版本的mplab c32编译器,它不提供优化代码。。只是猜测。当我删除attrib packed时,BDT_条目的大小为16字节,而使用packed attrib时,它的大小为10字节。