dmedine
dmedine

Reputation: 1563

direct copy of memorystream into something occupying the same memory as a byte[]?

I want to copy a section of a memory stream into an array of doubles. Something like:

MemoryStream stream = new(File.ReadAllBytes(pathToFileWithBinaryData));
int arrayLength = stream.Length/sizeof(double);
double[] array = new double[arrayLength];
byte[] buffer = new byte[sizeof(double)];
int i=0;
while(stream.Position < stream.Length)
{
  stream.Read(buffer, 0, sizeof(double));
  array[i] = BitConvert.ToDouble(buffer);
}

But, I don't want to copy the values from buffer to array one at a time. The C/C++ programmer in me is inclined to tackle it this way:

byte[] buffer = /* the memory address of the variable 'array' ??? */
stream.Read(buffer, 0, stream.Length);

and then I would have all the values in array because it is the memory that stream.Read copied into. Is there a way to do this? Then I could use stream.ReadAsync and be very happy.

Upvotes: 1

Views: 638

Answers (1)

dmedine
dmedine

Reputation: 1563

Thanks to the hints from @OlivierRogier, I found the solution that I was looking for. Here is an example program:

using System;
using System.IO;
using System.Runtime.InteropServices;

namespace MemoryEntangle
{
    [StructLayout(LayoutKind.Explicit)]
    public struct MemoryArea 
    {
        [FieldOffset(0)]
        public byte[] _buffer;

        [FieldOffset(0)]
        public double[] _array;
    }

    class Program
    {
        static void Main()
        {
            const int count = 10;
            MemoryArea ma = new();
            ma._buffer = new byte[count * sizeof(double)];
            //mab._array = new double[count];
            MemoryStream memoryStream = new();
            for (int i = 0; i < count; i++)
            {
                memoryStream.Write(BitConverter.GetBytes((double)i * .1));
                Console.WriteLine("{0}", (double)i * .1);
            }
            memoryStream.Position = 0;
            memoryStream.Read(ma._buffer, (int)memoryStream.Position, (int)memoryStream.Length);
            for (int i = 0; i < count; i++)
                Console.WriteLine("{0}", ma._array[i]);
        }
    }
}

Output:

0
0.1
0.2
0.30000000000000004
0.4
0.5
0.6000000000000001
0.7000000000000001
0.8
0.9
0
0.1
0.2
0.30000000000000004
0.4
0.5
0.6000000000000001
0.7000000000000001
0.8
0.9

Upvotes: 1

Related Questions