C# equivalent to C "union"?
typedef union byte_array { struct{byte byte1;byte byte2;byte byte3;byte byte4;}; struct{int int1;int int2;}; };byte_array |
...and access them by:
byte_array myarray; mybyte = myarray.byte1; myint = myarray.int1; |
typedef union byte_array { struct{byte byte1;byte byte2;byte byte3;byte byte4;}; struct{int int1;int int2;}; };byte_array |
byte_array myarray; mybyte = myarray.byte1; myint = myarray.int1; |
public class U { short s; //================================================== public U(short s) { this.s = s; } //================================================== public byte AsByte(byte index) { const short maskLeft = 0xF0; const short maskRight = 0x0F; switch (index) { // index: 0..3 case 0: return (byte)((maskLeft & s) >> 4); // shift right 4 bits case 1: return (byte)(maskRight & s); default: return 0;} } } |
For instance:
using System.Runtime.InteropServices;
[StructLayout(LayoutKind.Explicit)]
struct ByteArray {
[FieldOffset(0)]
public byte Byte1;
[FieldOffset(1)]
public byte Byte2;
[FieldOffset(2)]
public byte Byte3;
[FieldOffset(3)]
public byte Byte4;
[FieldOffset(4)]
public byte Byte5;
[FieldOffset(5)]
public byte Byte6;
[FieldOffset(6)]
public byte Byte7;
[FieldOffset(7)]
public byte Byte8;
[FieldOffset(0)]
public int Int1;
[FieldOffset(4)]
public int Int2;
}
One thing to be careful of is the endian-ness of the machine if you plan to run it on non-x86 platforms that may have differing endianness. See http://en.wikipedia.org/wiki/Endianness for an explanation.
You can actually do the following:
using System; [StructLayout(LayoutKind.Explicit)] [FieldOffset(1)] [FieldOffset(2)] [FieldOffset(3)] [FieldOffset(0)] [FieldOffset(2)] |
However, you need to be careful as the 'int' datatype in the .NET Framework is actually a 32-bit integer not 16-bit. So 2 bytes actually make up 1 short.
You may want to fix up FieldOffset for the Int2 field in your struct. It should be changed from 1 to 4.
Thanks for the help!
So, to reference the "int1" above, would I do the following?
myint = byte_array.int1 |
I will modify the structure for "short" instead of "int" since the other end of the USB link thinks ints are 16 bits...;)
Thanks again!