C
Chuck Bowling
I have a struct that i want to emulate a C++ style union:
[StructLayout(LayoutKind.Explicit)]
public struct Samp
{
[FieldOffset(0)] public byte[] byteBuf;
[FieldOffset(0)] public int[] intBuf;
public Samp(int sz)
{
byteBuf = new byte[sz];
intBuf = new int[sz];
}
}
To be honest, i don't really understand what's going on here. My
understanding is that an 'int' is 32 bits. A byte is 8 bits. The union of a
'int' with a byte array should only require 4 bytes. Therefore, a byte array
of 8 should be able to hold 2 ints. But, if i try the following:
[StructLayout(LayoutKind.Explicit)]
public struct Samp
{
[FieldOffset(0)] public byte[] byteBuf;
[FieldOffset(0)] public int[] intBuf;
public Samp(int sz)
{
byteBuf = new byte[sz];
intBuf = new int[sz/4]; // note smaller size
}
}
and access the byte array beyond byte[3], I get an OutOfRangeException.
Does this mean that I have to allocate 4 bytes for every byte that I
allocate in the byte array to accomodate the ints? That kind of defeats one
of the benefits of unions...
[StructLayout(LayoutKind.Explicit)]
public struct Samp
{
[FieldOffset(0)] public byte[] byteBuf;
[FieldOffset(0)] public int[] intBuf;
public Samp(int sz)
{
byteBuf = new byte[sz];
intBuf = new int[sz];
}
}
To be honest, i don't really understand what's going on here. My
understanding is that an 'int' is 32 bits. A byte is 8 bits. The union of a
'int' with a byte array should only require 4 bytes. Therefore, a byte array
of 8 should be able to hold 2 ints. But, if i try the following:
[StructLayout(LayoutKind.Explicit)]
public struct Samp
{
[FieldOffset(0)] public byte[] byteBuf;
[FieldOffset(0)] public int[] intBuf;
public Samp(int sz)
{
byteBuf = new byte[sz];
intBuf = new int[sz/4]; // note smaller size
}
}
and access the byte array beyond byte[3], I get an OutOfRangeException.
Does this mean that I have to allocate 4 bytes for every byte that I
allocate in the byte array to accomodate the ints? That kind of defeats one
of the benefits of unions...