我想将内存流的一段复制到双精度数组中。比如:
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);
}
但是,我不想一次一个地从buffer
复制值到array
。我内心的C/c++程序员倾向于这样处理它:
byte[] buffer = /* the memory address of the variable 'array' ??? */
stream.Read(buffer, 0, stream.Length);
然后我将拥有array
中的所有值,因为它是stream.Read
复制到的内存。有办法做到这一点吗?然后我可以使用stream.ReadAsync
,非常高兴。
感谢@OlivierRogier的提示,我找到了我正在寻找的解决方案。下面是一个示例程序:
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]);
}
}
}
输出:
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