Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In C# cast array without making a copy

Tags:

arrays

c#

casting

I have an array of shorts:

short[] data;

And I have a function that writes bytes to a file:

void Write(byte[] data);

I do not control this function and cannot change it. Is there a way to write my array of shorts without making a redundant copy first to convert it to bytes?

Something like that: Write((byte[])data);

I do not care about endianness. I want memory representation of shorts written to a file in whatever the machine representation of short is. I understand this kind of cast cannot work for any non-POD type that contains references, but shorts should be perfectly convertible. The cast should result in a byte array twice the size that points to the same memory.

If this is impossible in C#, is there anything in CLR that makes this impossible, or is it just C# limitation?

like image 798
kaalus Avatar asked Oct 23 '25 19:10

kaalus


1 Answers

I do not care about endianness. I want memory representation of shorts written to a file in whatever the machine representation of short is.

This is the first impossible thing - endianness changes the memory representation, so reading from successive byte addresses starting at the address of the first short in the array will result in different byte patterns depending on the machine endianness.

The second impossible thing is that arrays in the CLR have type and length information encoded with the data. You cannot change this header information, or else you would break the garbage collector. So given a short[] array, you cannot convert it to a byte[] array. You might get to a byte pointer using C++ clr or unsafe code, but you still won't get to a CLR array.

If you really cannot control the code which takes the byte array, you might be able to change the code manipulating the shorts. Using a MemoryStream over the byte array would allow you to read and write data to it, you could wrap the array as an IList<short>, or you could just create accessor extension functions to get the data as shorts.

public sealed class ShortList :IList<short>
{
    private readonly byte[] _array;

    public short this[int index]
    {
        get { return (short)_array[index/2]<<8 | _array[index/2+1] ; }
    }

    public int Count
    {
        get { return _array.Length/2; }
    }

    ... many more methods in IList
like image 76
Pete Kirkham Avatar answered Oct 26 '25 08:10

Pete Kirkham



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!