Here by "directly" I mean without temporary byte[] array.
The problem is, for example I have array of ints or doubles on the disk, so currently I create two arrays -- byte array and int array (in case of ints). The former is just for reading, the latter is the actual output.
Since Stream can read only to byte array I read it to the first array, than copy all the data to the second. It works, but it really hurts me (I am not talking about performance here).
So, how to read the array without temporary array? Using C# unsafe context is fine for me.
So far I tried two approaches: I looked if it is possible to create an array reusing allocated memory and second which looked more promising -- I could get pointer to the result/second array and in unsafe context I could cast it to byte* pointer. Considering my needs it is 100% safe and valid, however byte* pointer is not a byte[] array in C# world and I cannot find the way to cast pointer to array.
Code:
void ReadStuff(Stream stream, double[] data)
{
var dataBytes = new byte[data.Length * sizeof(double)];
stream.Read(dataBytes, 0, dataBytes.Length);
Buffer.BlockCopy(dataBytes, 0, data, 0, dataBytes.Length);
// ...
}
Span<byte>byte*in C, you also work like that. Someone allocated that array. And since you use the same buffer each time, there's no waste or extra GC involved even with a single stream. MemoryPool is used when you need to conserve memory across thousands of streams, eg when you have a high-traffic web service. So what's the real problem? Why look at abyte*? If you want to avoid copying, you useStream.Read(Span<byte>)BinaryReadercan be used to read integers and bytes from part of stream learn.microsoft.com/en-us/dotnet/api/system.io.binaryreader