1

我正在用Free Pascal为我的游戏编写一个SDL /input 库,但我遇到了一个问题。

我有一个变体记录,当我访问其中的一个元素时,它会更改其他元素。

记录类型为:

tInput = Record
    case Device: TInputDevice of
        ID_KeyOnce, ID_KeyCont:                     (Key:         TSDLKey);
        ID_MouseButton:                             (MouseButton: Byte);
        ID_MouseAxis, ID_JoyAxis,
          ID_JoyBall, ID_JoyHat:                    (Axis:        Byte);
        ID_JoyButton, ID_JoyButtonOnce, ID_JoyAxis,
          ID_JoyHat, ID_JoyBall:                    (Which:       Byte);
        ID_JoyButton, ID_JoyButtonOnce:             (Button:      Byte);

结尾;

崩溃的代码是:

with Input do begin
    Device := ID_JoyAxis;
    Which  := 0;
    Axis   := 1;
end;

当轴设置为一时,记录中的所有其他变量都变为一二!

这是一个已知的错误?或者一些我不知道的功能?还是我搞砸了什么?

4

1 回答 1

1

这称为此类记录声明的联合和预期行为。

case Device : TInputDevice of

...是这里的“魔法”。

在联合中,成员的存储是“共享的”。

编辑:根据字节偏移量记录您的记录(...假设sizeof(TSDLKey) = 4):

------------------------------------------------
00 | Key | MouseButton | Axis | Which | Button |
---|     |-------------|------|-------|--------|
01 |     |             |      |       |        |
---|     |-------------|------|-------|--------|
02 |     |             |      |       |        |
---|     |-------------|------|-------|--------|
03 |     |             |      |       |        |
------------------------------------------------

By the rules I know, TInputDevice should be an enum type, otherwise you'd have to explicitly give Integer there:

type xyz = record
  case integer of
  0: (foo: Byte);
  1: (bar: Integer);
end;

NB: it is customary for variant types to have one member describe which of the union members should be picked and valid (nested unions).

于 2011-03-02T03:39:34.080 回答