I have a byte array with data like this (managed code)
byte[] test = {0xA,0xB,0xC,0xD}; // data is much longer...
If I explicit do like this, LINQ will create a copy from original array.
var test2 = test.Skip(1).Take(2).ToArray();
and I need a part of it, but without creating a copy as new array.
Inspired by this, Get a Array subset without copying like in C with pointers
var test2 = test.Skip(1).Take(2);
it works, but the result is IEnumerable and I need a pure byte[].
So basically the goal is to have a real chunk of original array (not a copy of chunk) and if I modify a element, to be reflected in chunk too (like having pointers in C)
Is it possible to convert IEnumerable to byte[] without copy?
Is it possible to do it otherwise (no LINQ)?
Thank you in advance!
CodePudding user response:
It seems that you are looking for Span or Memory<byte>
:
byte[] test = { 0xA, 0xB, 0xC, 0xD };
// Span is some kind of c-like pointer to the array
// first 2 - skip 2 items
// second 2 - take 2 items
Span<byte> span = new Span<byte>(test, 2, 2);
// We modify the array item...
test[3] = 0xFF;
// ... and span reflects the modification
// Note that we have skipped 2 items, that's why span[1], not span[3]
byte result = span[1]; // 0xFF