What would be the best way to simulate a Union?

BlitzMax Forums/BlitzMax Programming/What would be the best way to simulate a Union?

sswift(Posted 2009) [#1]
I've got these structs I need to convert from C, and the first one as you can see has a union. I could define this as Field Data:Byte[22], since that is the size of the largest of the structs it could potentially contain, but then I wouldn't have an easy way to access the fields for that data.

typedef struct tagRAWINPUT { 
    RAWINPUTHEADER    header; 
    union {
             RAWMOUSE    mouse; 
             RAWKEYBOARD keyboard; 
             RAWHID      hid; 
            } data;
} RAWINPUT, *PRAWINPUT; *LPRAWINPUT;

typedef struct tagRAWHID {
    DWORD dwSizeHid;
    DWORD dwCount;
    BYTE bRawData;
} RAWHID, **LPRAWHID;


typedef struct tagRAWKEYBOARD {
    USHORT MakeCode;
    USHORT Flags;
    USHORT Reserved;
    USHORT VKey;
    UINT Message;
    ULONG ExtraInformation;
} RAWKEYBOARD, *PRAWKEYBOARD, *LPRAWKEYBOARD;

typedef struct tagRAWMOUSE { 
  USHORT    usFlags; 
  union {
         ULONG    ulButtons;
             struct {
                       USHORT usButtonFlags;
                       USHORT usButtonData;
                       };
  };
  ULONG ulRawButtons;
  LONG  lLastX;
  LONG  lLastY;
  ULONG ulExtraInformation;
} RAWMOUSE, *PRAWMOUSE, *LPRAWMOUSE;


So, any suggestions?


Arowx(Posted 2009) [#2]
What about a bank, then you can peek the relevant data elements when you need them or possibly set up pointers to the elements within the bank?


sswift(Posted 2009) [#3]
Hm... an array should work fine with pointers. And pointers are an interesting avenue to explore. But they're also a bit too complicated for what I want to do here.

If I actually need all those types then it might be worth it, but I think in this particular case I can just get away with removing that union from the first type and replacing it with the fields in the RAWMOUSE type, which is both the largest, and the one that has the data I need.


smilertoo(Posted 2009) [#4]
You can simulate a union by taking money from each worker, then doing nothing for them as long as you're ok.


sswift(Posted 2009) [#5]
I already made the union joke. :-)