从 v-usb 项目了解 usbjoy 库中的数据结构

Understanding data structure in usbjoy library from v-usb project

大家好。

我正在尝试制作自己的操纵杆,所以我一直在寻找参考资料,然后我从 v-usb wiki 页面 (http://vusb.wikidot.com/project:usbjoy) 找到了 usbjoy 项目。

然后,我在网站的 zip 文件中找到了按钮的数据结构,取自 common.h。

typedef struct
{
  uchar x; //Byte-0, ユ (0...255)
  uchar y; //Byte-1, Y (0...255)
        uchar z; //Byte-2, Handle-1 (0...255)
  uchar p; //Byte-3, Handle-2 (0...255)

  union {
    uchar buttons; //Byte-4, buttons 8
    struct
    {
      uchar btn1:    1; //0, 1
      uchar btn2:    1; //0, 1
      uchar btn3:    1; //0, 1
      uchar btn4:    1; //0, 1
      uchar btn5:    1; //0, 1
      uchar btn6:    1; //0, 1
      uchar btn7:    1; //0, 1
      uchar btn8:    1; //0, 1
    } b;
  } u;
        union {
    uchar but; //Byte-5, buttons 4
    struct
    {
      uchar btn9:    1; //0, 1
      uchar btn10:   1; //0, 1
      uchar btn11:   1; //0, 1
      uchar btn12:   1; //0, 1
      uchar padding: 4; //Not use
                } b;
  } w;
} t_PsxController;

我知道 x 和 y 用于左模拟垫,z 和 p 用于右模拟垫,u 和 w 用于按钮。我的问题是:

  1. 为什么将 u 和 w 声明为并集?
  2. 联合中的结构会被使用吗?
  3. t_PsxController 的大小是多少?
  4. 最后,uchar btn1: 1; 中的冒号及其下方的代码是什么意思?

Why are u and w declared as unions?

您将同时使用八个按钮中的一个按钮,对吗?只需要访问数据结构的一个成员,所以使用联合。理解结构和联合之间的difference。操纵杆可用于左垫、右垫和

Will the struct inside the unions ever be used?

是的,它代表不同的按钮,因此将被使用。

What is the size of t_PsxController?

t_PsxController 是结构,结构的最大大小是结构所有成员的总和。

And finally, what do colons in uchar btn1: 1; and codes below it mean?

union内部结构uchar btn1: 1表示占用1位的unsigned char位域

union内部结构uchar padding: 4代表unsigned char位域,占4位

t_PsxController 是一个 6 字节大小的结构。每个字节都在您发布的代码的注释中编号。某些行中的冒号 : 指示编译器将一定数量的位(在本例中为 1 或 4)分配给项目,而不是整个字节。这使得每个联合只有 1 个字节长。

t_PsxController controller;

将声明一个名为 controller 的结构,您稍后可以使用它。它有 6 个字节长。

要访问结构的成员,请使用 . 点运算符。您使用的标识符将决定您访问的是哪个联盟成员。例如,

controller.x = 23; // assigns a value to the byte 0
controller.u.b.btn1 = 1; // assigns a 1 to the first bit of the byte 4
uchar x = controller.u.buttons; // assigns 128 to x

您可能希望在某些时候使用指向 controller 的指针,尤其是在传递给函数时。然后,您需要使用 -> 运算符以及 . 点。

t_PsxController *ctlr = controller;

ctlr->u.b.btn2 = 1; // Now ctlr->u.buttons is 192