C++ unions

Miscellaneous Forums/General Discussion/C++ unions

Hi.

I'm trying to write a type based on a C++ struct and came across union. I had a look on Google but couldn't really understand what it was (I dont like C++ and it's quite late :P).

I'm reading file headers into the types and just want to know whether it's possible to just ignore the union and enter the fields in it into the type as though the union keyword was never there. For example if the C++ struct is:

typedef struct _Blah_Struct{
    BYTE Var1;
    union {
       BYTE uVar1;
    }
    BYTE var2;
} Blah_Struct;


Could the Type be:

Type BlahStruct
    Field var1:Byte
    Field uVar1:Byte
    Field var2:Byte
End Type


Thanks for any help - and I hope i make sense!

Matt

The size of a union is the size of its largest member (plus you have to consider its packing).

E.g., the size of this union
union {
  int a;
  short b;
  char c;
} someUnion;

Would be 4.

The size of this union
union {
int a[24];
long b;
double c;
} someUnion2;

Would be sizeof(int)*24.

If you had an odd number of bytes to a union, you would probably want to take into consideration packing as well. In your case, it might be 2 bytes unless there was some option specified in the library you're wrapping. Maybe just the struct is packed and the union has no packing options, but then that might prove to be somewhat of an odd position when typedef'ing unions, so I'd read up on it.

Ok, I may be totally off the mark (i'm just pasting together what you've said and other things i've read to come up with this) but would you only assign one of the union's variables a value?

So for your second example if 'b' had a value then 'a' and 'c' wouldn't?

Sortof.

If b had a value, then a[0], a[1], and c would have values, but they wouldn't be the same number you assigned to b.

Basically, unions are ambiguous types. They can be multiple things but still be small because each member shares the same memory as its other members.

For example, if you did
union {
  int a;
  int b;
} someUnion;

then it would be pointless because a and b are 1) the same type and 2) sharing the same memory, so they will always be the same value.

So if you did this
union {
  int a;
  float b;
} someUnion;

Then if you assigned a the value 0x00700000 then b's hex value would be 0x00700000, although the value will be different.

When you use a union, you usually want to include a type enum or a strict set of rules for how it's to be used. If the union being passed to something is ambiguous in its usage, then you'll pretty much need an enum to handle it correctly.

Ok, I think I get it now thanks!

I suppose the real test of how well I understand it is whether what I'm doing works when it's finished :P

Thanks again,
Matt

Unions are mostly only useful for space optimizations. You could use a bank to emulate a union, but chances are you can get by without 'em.