CSharp超大数组的解决方案

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
public class LongArray<T> : IDisposable where T : struct
{
private IntPtr _head;
private Int64 _capacity;
private UInt64 _bytes;
private Int32 _elementSize;

public LongArray(long capacity)
{
if (_capacity < 0) throw new ArgumentException("The capacity can not be negative");
_elementSize = SizeOf(default(T));
_capacity = capacity;
_bytes = (ulong)capacity * (ulong)_elementSize;
_head = AllocHGlobal((IntPtr)_bytes);
}

public T this[long index]
{
get
{
IntPtr p = _getAddress(index);
T val = (T)System.Runtime.InteropServices.Marshal.PtrToStructure(p, typeof(T));
return val;
}
set
{
IntPtr p = _getAddress(index);
StructureToPtr(value, p, true);
}
}

protected bool disposed = false;
public void Dispose()
{
if (!disposed)
{
FreeHGlobal((IntPtr)_head);
disposed = true;
}
}

public IntPtr _getAddress(long index)
{
if (disposed)
throw new ObjectDisposedException("Can't access the array once it has been disposed!");
if (index < 0)
throw new IndexOutOfRangeException("Negative indices are not allowed");
if (!(index < _capacity))
throw new IndexOutOfRangeException("Index is out of bounds of this array");
return (IntPtr)((ulong)_head + (ulong)index * (ulong)(_elementSize));
}
}