简体   繁体   中英

C# in-place cast `int[]` array to `byte[]` array

I have an array of some type ( short[] , int[] , or similar base type). I want to send it through a stream, so I need it to be byte[] . The standard solution seems to be creating a new byte[] array, and use BitConverter . The problem with this approach is performance and memory usage - it requires allocating all new memory, copying into the new memory, and then writing the byte[] to the stream.

I very much want to use the original backing memory of the int[] array as a byte[] array so I can send it in-place. I am willing to enforce the requirement that the sending and receiving system must be the same endianness, for the sake of this very obvious and very significant performance difference.

Is there some way to treat an array of int[] or similar, as a byte[] in-place?

If you can use Span<T> (.net core 3+):

void Send(int[] data)
{
    ReadOnlySpan<byte> byteRef = MemoryMarshal.AsBytes(data.AsSpan());
    _stream.Write(byteRef);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM