A C# application needs to allocate memory and treat that block as either an array of bytes or an array of shorts.
Here's what I've tried. A structure was declared that was supposed to have a byte[] and a short[] occupying the same memory space.
At run time, the amount of memory that would be required in terms of bytes is determined and allocated. The structure is loaded with that memory block.
The above mechanism fails in that the bytes member appears to share the low byte of the shorts member that shares the same index. If 256 bytes are allocated there are also 256 shorts is is not what we want. The expectation is that each shorts member would share union data with the bytes array members whose indexes are [n/2] and [n/2+].
As an example, if bytes[5] is 0xe0, bytes[10] is 0x11 and bytes[11] is 0x22 then shorts[5] should be 0x2211. It is not. It is 0xe0.
Any suggestions on how to accomplish this?
Here's what I've tried. A structure was declared that was supposed to have a byte[] and a short[] occupying the same memory space.
C#:
[StructLayout(LayoutKind.Explicit)]
struct ByteToShortArray
{
[FieldOffset(0)]
public byte[] bytes;
[FieldOffset(0)]
public short[] shorts;
}
C#:
ByteToShortArray byteToShortArray = new ByteToShortArray();
buffer = new byte[acquisitionSize];
byteToShortArray.bytes = buffer;
As an example, if bytes[5] is 0xe0, bytes[10] is 0x11 and bytes[11] is 0x22 then shorts[5] should be 0x2211. It is not. It is 0xe0.
Any suggestions on how to accomplish this?
Last edited by a moderator: