gpt4 book ai didi

c# - 二维字节数组可以做成一个巨大的连续字节数组吗?

转载 作者:行者123 更新时间:2023-11-30 14:03:42 25 4
gpt4 key购买 nike

我在内存中有一个非常大的二维字节数组,

byte MyBA = new byte[int.MaxValue][10];

有什么方法(可能不安全)可以让 C# 认为这是一个巨大的连续字节数组吗?我想这样做,以便我可以将它传递给 MemoryStream,然后传递给 BinaryReader

MyReader = new BinaryReader(MemoryStream(*MyBA)) //Syntax obviously made-up here

最佳答案

我不相信 .NET 提供了这个,但是实现您自己的 System.IO.Stream 的实现应该相当容易,它可以无缝切换支持数组。以下是(未经测试的)基础知识:

public class MultiArrayMemoryStream: System.IO.Stream
{
byte[][] _arrays;
long _position;
int _arrayNumber;
int _posInArray;

public MultiArrayMemoryStream(byte[][] arrays){
_arrays = arrays;
_position = 0;
_arrayNumber = 0;
_posInArray = 0;
}

public override int Read(byte[] buffer, int offset, int count){
int read = 0;
while(read<count){
if(_arrayNumber>=_arrays.Length){
return read;
}
if(count-read <= _arrays[_arrayNumber].Length - _posInArray){
Buffer.BlockCopy(_arrays[_arrayNumber], _posInArray, buffer, offset+read, count-read);
_posInArray+=count-read;
_position+=count-read;
read=count;
}else{
Buffer.BlockCopy(_arrays[_arrayNumber], _posInArray, buffer, offset+read, _arrays[_arrayNumber].Length - _posInArray);
read+=_arrays[_arrayNumber].Length - _posInArray;
_position+=_arrays[_arrayNumber].Length - _posInArray;
_arrayNumber++;
_posInArray=0;
}
}
return count;
}

public override long Length{
get {
long res = 0;
for(int i=0;i<_arrays.Length;i++){
res+=_arrays[i].Length;
}
return res;
}
}

public override long Position{
get { return _position; }
set { throw new NotSupportedException(); }
}

public override bool CanRead{
get { return true; }
}

public override bool CanSeek{
get { return false; }
}

public override bool CanWrite{
get { return false; }
}

public override void Flush(){
}

public override void Seek(long offset, SeekOrigin origin){
throw new NotSupportedException();
}

public override void SetLength(long value){
throw new NotSupportedException();
}

public override void Write(byte[] buffer, int offset, int count){
throw new NotSupportedException();
}
}

另一种解决 2^31 字节大小限制的方法是 UnmanagedMemoryStream它在非托管内存缓冲区(可能与操作系统支持的一样大)之上实现 System.IO.Stream。这样的事情可能会起作用(未经测试):

var fileStream = new FileStream("data", 
FileMode.Open,
FileAccess.Read,
FileShare.Read,
16 * 1024,
FileOptions.SequentialScan);
long length = fileStream.Length;
IntPtr buffer = Marshal.AllocHGlobal(new IntPtr(length));
var memoryStream = new UnmanagedMemoryStream((byte*) buffer.ToPointer(), length, length, FileAccess.ReadWrite);
fileStream.CopyTo(memoryStream);
memoryStream.Seek(0, SeekOrigin.Begin);
// work with the UnmanagedMemoryStream
Marshal.FreeHGlobal(buffer);

关于c# - 二维字节数组可以做成一个巨大的连续字节数组吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3651501/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com