2
using System.Runtime.InteropServices;
3
using System.Collections;
4
using System.Collections.Generic;
5
using System.Diagnostics;
10
/// Represents unmanaged memory, containing an array of a given structure.
12
/// <typeparam name="T">Structuretype represented by the instance.</typeparam>
14
/// <see cref="System.Boolean"/> and <see cref="System.Char"/> can not be marshalled.
16
/// Use <see cref="System.Int32"/> instead of <see cref="System.Boolean"/> and
17
/// <see cref="System.Byte"/> instead of <see cref="System.Char"/>.
19
public unsafe class MemoryArray<T> : IDisposable, ICloneable, ICollection, IEnumerable<T>, IEquatable<MemoryArray<T>> where T : struct
22
/// Baseaddress of the wrapped memory.
24
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
25
protected byte* baseAddress;
28
/// Number of elements being wrapped.
30
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
34
/// Size, in bytes, of each element.
36
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
37
private static readonly int size;
40
/// Array of <b>T</b> containing a single element.
41
/// The array is used as a workaround, because there are no pointer for generic types.
43
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
47
/// Pointer to the element of <b>buffer</b>.
49
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
53
/// Handle for pinning <b>buffer</b>.
55
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
56
protected GCHandle handle;
59
/// Indicates whether the wrapped memory is handled like a bitfield.
61
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
62
protected readonly bool isOneBit;
65
/// Indicates whther the wrapped memory is handles like 4-bit blocks.
67
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
68
protected readonly bool isFourBit;
71
/// An object that can be used to synchronize access to the <see cref="MemoryArray<T>"/>.
73
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
74
protected object syncRoot = null;
79
long marshalledSize = Marshal.SizeOf(typeof(T));
81
Marshal.UnsafeAddrOfPinnedArrayElement(dummy, 1).ToInt64() -
82
Marshal.UnsafeAddrOfPinnedArrayElement(dummy, 0).ToInt64();
83
if (marshalledSize != structureSize)
85
throw new NotSupportedException(
86
"The desired type can not be handled, " +
87
"because its managed and unmanaged size in bytes are different.");
90
size = (int)marshalledSize;
94
/// Initializes a new instance.
96
protected MemoryArray()
101
/// Initializes a new instance of the <see cref="MemoryArray<T>"/> class.
103
/// <param name="baseAddress">Address of the memory block.</param>
104
/// <param name="length">Length of the array.</param>
105
/// <exception cref="ArgumentNullException">
106
/// <paramref name="baseAddress"/> is null.</exception>
107
/// <exception cref="ArgumentOutOfRangeException">
108
/// <paramref name="length"/> is less or equal zero.</exception>
109
/// <exception cref="NotSupportedException">
110
/// The type is not supported.</exception>
111
public MemoryArray(IntPtr baseAddress, int length)
112
: this(baseAddress.ToPointer(), length)
117
/// Initializes a new instance of the <see cref="MemoryArray<T>"/> class.
119
/// <param name="baseAddress">Address of the memory block.</param>
120
/// <param name="length">Length of the array.</param>
121
/// <exception cref="ArgumentNullException">
122
/// <paramref name="baseAddress"/> is null.</exception>
123
/// <exception cref="ArgumentOutOfRangeException">
124
/// <paramref name="length"/> is less or equal zero.</exception>
125
/// <exception cref="NotSupportedException">
126
/// The type is not supported.</exception>
127
public MemoryArray(void* baseAddress, int length)
129
if (typeof(T) == typeof(FI1BIT))
133
else if (typeof(T) == typeof(FI4BIT))
138
if (baseAddress == null)
140
throw new ArgumentNullException("baseAddress");
144
throw new ArgumentOutOfRangeException("length");
147
this.baseAddress = (byte*)baseAddress;
148
this.length = (int)length;
150
if (!isOneBit && !isFourBit)
152
// Create an array containing a single element.
153
// Due to the fact, that it's not possible to create pointers
154
// of generic types, an array is used to obtain the memory
155
// address of an element of T.
156
this.buffer = new T[1];
157
// The array is pinned immediately to prevent the GC from
158
// moving it to a different position in memory.
159
this.handle = GCHandle.Alloc(buffer, GCHandleType.Pinned);
160
// The array and its content have beed pinned, so that its address
161
// can be safely requested and stored for the whole lifetime
163
this.ptr = (byte*)handle.AddrOfPinnedObject();
168
/// Frees the allocated <see cref="System.Runtime.InteropServices.GCHandle"/>.
176
/// Tests whether two specified <see cref="MemoryArray<T>"/> structures are equivalent.
178
/// <param name="left">The <see cref="MemoryArray<T>"/> that is to the left of the equality operator.</param>
179
/// <param name="right">The <see cref="MemoryArray<T>"/> that is to the right of the equality operator.</param>
181
/// <b>true</b> if the two <see cref="MemoryArray<T>"/> structures are equal; otherwise, <b>false</b>.
183
public static bool operator ==(MemoryArray<T> left, MemoryArray<T> right)
185
if (object.ReferenceEquals(left, right))
189
if (object.ReferenceEquals(right, null) ||
190
object.ReferenceEquals(left, null) ||
191
(left.length != right.length))
195
if (left.baseAddress == right.baseAddress)
199
return FreeImage.CompareMemory(left.baseAddress, right.baseAddress, (uint)left.length);
203
/// Tests whether two specified <see cref="MemoryArray<T>"/> structures are different.
205
/// <param name="left">The <see cref="MemoryArray<T>"/> that is to the left of the inequality operator.</param>
206
/// <param name="right">The <see cref="MemoryArray<T>"/> that is to the right of the inequality operator.</param>
208
/// <b>true</b> if the two <see cref="MemoryArray<T>"/> structures are different; otherwise, <b>false</b>.
210
public static bool operator !=(MemoryArray<T> left, MemoryArray<T> right)
212
return (!(left == right));
216
/// Gets the value at the specified position.
218
/// <param name="index">A 32-bit integer that represents the position
219
/// of the array element to get.</param>
220
/// <returns>The value at the specified position.</returns>
221
/// <exception cref="ArgumentOutOfRangeException">
222
/// <paramref name="index"/> is outside the range of valid indexes
223
/// for the unmanaged array.</exception>
224
public T GetValue(int index)
226
if ((index >= this.length) || (index < 0))
228
throw new ArgumentOutOfRangeException("index");
231
return GetValueInternal(index);
234
private T GetValueInternal(int index)
239
return (T)(object)(FI1BIT)(((baseAddress[index / 8] & ((1 << (7 - (index % 8))))) == 0) ? 0 : 1);
243
return (T)(object)(FI4BIT)(((index % 2) == 0) ? (baseAddress[index / 2] >> 4) : (baseAddress[index / 2] & 0x0F));
247
CopyMemory(ptr, baseAddress + (index * size), size);
253
/// Sets a value to the element at the specified position.
255
/// <param name="value">The new value for the specified element.</param>
256
/// <param name="index">A 32-bit integer that represents the
257
/// position of the array element to set.</param>
258
/// <exception cref="ArgumentOutOfRangeException">
259
/// <paramref name="index"/> is outside the range of valid indexes
260
/// for the unmanaged array.</exception>
261
public void SetValue(T value, int index)
263
if ((index >= this.length) || (index < 0))
265
throw new ArgumentOutOfRangeException("index");
267
SetValueInternal(value, index);
270
private void SetValueInternal(T value, int index)
275
if ((FI1BIT)(object)value != 0)
277
baseAddress[index / 8] |= (byte)(1 << (7 - (index % 8)));
281
baseAddress[index / 8] &= (byte)(~(1 << (7 - (index % 8))));
286
if ((index % 2) == 0)
288
baseAddress[index / 2] = (byte)((baseAddress[index / 2] & 0x0F) | ((FI4BIT)(object)value << 4));
292
baseAddress[index / 2] = (byte)((baseAddress[index / 2] & 0xF0) | ((FI4BIT)(object)value & 0x0F));
298
CopyMemory(baseAddress + (index * size), ptr, size);
303
/// Gets the values at the specified position and length.
305
/// <param name="index">A 32-bit integer that represents the position
306
/// of the array elements to get.</param>
307
/// <param name="length"> A 32-bit integer that represents the length
308
/// of the array elements to get.</param>
309
/// <returns>The values at the specified position and length.</returns>
310
/// <exception cref="ArgumentOutOfRangeException">
311
/// <paramref name="index"/> is outside the range of valid indexes
312
/// for the unmanaged array or <paramref name="length"/> is greater than the number of elements
313
/// from <paramref name="index"/> to the end of the unmanaged array.</exception>
314
public T[] GetValues(int index, int length)
317
if ((index >= this.length) || (index < 0))
319
throw new ArgumentOutOfRangeException("index");
321
if (((index + length) > this.length) || (length < 1))
323
throw new ArgumentOutOfRangeException("length");
326
T[] data = new T[length];
327
if (isOneBit || isFourBit)
329
for (int i = 0; i < length; i++)
331
data[i] = GetValueInternal(i);
336
GCHandle handle = GCHandle.Alloc(data, GCHandleType.Pinned);
337
byte* dst = (byte*)Marshal.UnsafeAddrOfPinnedArrayElement(data, 0);
338
CopyMemory(dst, baseAddress + (size * index), size * length);
345
/// Sets the values at the specified position.
347
/// <param name="values">An array containing the new values for the specified elements.</param>
348
/// <param name="index">A 32-bit integer that represents the position
349
/// of the array elements to set.</param>
350
/// <exception cref="ArgumentNullException">
351
/// <paramref name="values"/> is a null reference (Nothing in Visual Basic).</exception>
352
/// <exception cref="ArgumentOutOfRangeException">
353
/// <paramref name="index"/> is outside the range of valid indexes
354
/// for the unmanaged array or <paramref name="values.Length"/> is greater than the number of elements
355
/// from <paramref name="index"/> to the end of the array.</exception>
356
public void SetValues(T[] values, int index)
361
throw new ArgumentNullException("values");
363
if ((index >= this.length) || (index < 0))
365
throw new ArgumentOutOfRangeException("index");
367
if ((index + values.Length) > this.length)
369
throw new ArgumentOutOfRangeException("values.Length");
372
if (isOneBit || isFourBit)
374
for (int i = 0; i != values.Length; )
376
SetValueInternal(values[i++], index++);
381
GCHandle handle = GCHandle.Alloc(values, GCHandleType.Pinned);
382
byte* src = (byte*)Marshal.UnsafeAddrOfPinnedArrayElement(values, 0);
383
CopyMemory(baseAddress + (index * size), src, size * length);
389
/// Copies the entire array to a compatible one-dimensional <see cref="System.Array"/>,
390
/// starting at the specified index of the target array.
392
/// <param name="array">The one-dimensional <see cref="System.Array"/> that is the destination
393
/// of the elements copied from <see cref="MemoryArray<T>"/>.
394
/// The <see cref="System.Array"/> must have zero-based indexing.</param>
395
/// <param name="index">The zero-based index in <paramref name="array"/>
396
/// at which copying begins.</param>
397
public void CopyTo(Array array, int index)
402
throw new InvalidCastException("array");
406
CopyTo((T[])array, 0, index, length);
408
catch (ArgumentOutOfRangeException ex)
410
throw new ArgumentException(ex.Message, ex);
415
/// Copies a range of elements from the unmanaged array starting at the specified
416
/// <typeparamref name="sourceIndex"/> and pastes them to <paramref name="array"/>
417
/// starting at the specified <paramref name="destinationIndex"/>.
418
/// The length and the indexes are specified as 32-bit integers.
420
/// <param name="array">The array that receives the data.</param>
421
/// <param name="sourceIndex">A 32-bit integer that represents the index
422
/// in the unmanaged array at which copying begins.</param>
423
/// <param name="destinationIndex">A 32-bit integer that represents the index in
424
/// the destination array at which storing begins.</param>
425
/// <param name="length">A 32-bit integer that represents the number of elements to copy.</param>
426
/// <exception cref="ArgumentNullException">
427
/// <paramref name="array"/> is a null reference (Nothing in Visual Basic).</exception>
428
/// <exception cref="ArgumentOutOfRangeException">
429
/// <paramref name="sourceIndex"/> is outside the range of valid indexes
430
/// for the unmanaged array or <paramref name="length"/> is greater than the number of elements
431
/// from <paramref name="index"/> to the end of the unmanaged array
432
/// <para>-or-</para>
433
/// <paramref name="destinationIndex"/> is outside the range of valid indexes
434
/// for the array or <paramref name="length"/> is greater than the number of elements
435
/// from <paramref name="index"/> to the end of the array.
437
public void CopyTo(T[] array, int sourceIndex, int destinationIndex, int length)
442
throw new ArgumentNullException("array");
444
if ((sourceIndex >= this.length) || (sourceIndex < 0))
446
throw new ArgumentOutOfRangeException("sourceIndex");
448
if ((destinationIndex >= array.Length) || (destinationIndex < 0))
450
throw new ArgumentOutOfRangeException("destinationIndex");
452
if ((sourceIndex + length > this.length) ||
453
(destinationIndex + length > array.Length) ||
456
throw new ArgumentOutOfRangeException("length");
459
if (isOneBit || isFourBit)
461
for (int i = 0; i != length; i++)
463
array[destinationIndex++] = GetValueInternal(sourceIndex++);
468
GCHandle handle = GCHandle.Alloc(array, GCHandleType.Pinned);
469
byte* dst = (byte*)Marshal.UnsafeAddrOfPinnedArrayElement(array, destinationIndex);
470
CopyMemory(dst, baseAddress + (size * sourceIndex), size * length);
476
/// Copies a range of elements from the array starting at the specified
477
/// <typeparamref name="sourceIndex"/> and pastes them to the unmanaged array
478
/// starting at the specified <paramref name="destinationIndex"/>.
479
/// The length and the indexes are specified as 32-bit integers.
481
/// <param name="array">The array that holds the data.</param>
482
/// <param name="sourceIndex">A 32-bit integer that represents the index
483
/// in the array at which copying begins.</param>
484
/// <param name="destinationIndex">A 32-bit integer that represents the index in
485
/// the unmanaged array at which storing begins.</param>
486
/// <param name="length">A 32-bit integer that represents the number of elements to copy.</param>
487
/// <exception cref="ArgumentNullException">
488
/// <paramref name="array"/> is a null reference (Nothing in Visual Basic).</exception>
489
/// <exception cref="ArgumentOutOfRangeException">
490
/// <paramref name="sourceIndex"/> is outside the range of valid indexes
491
/// for the array or <paramref name="length"/> is greater than the number of elements
492
/// from <paramref name="index"/> to the end of the array
493
/// <para>-or-</para>
494
/// <paramref name="destinationIndex"/> is outside the range of valid indexes
495
/// for the unmanaged array or <paramref name="length"/> is greater than the number of elements
496
/// from <paramref name="index"/> to the end of the unmanaged array.
498
public void CopyFrom(T[] array, int sourceIndex, int destinationIndex, int length)
503
throw new ArgumentNullException("array");
505
if ((destinationIndex >= this.length) || (destinationIndex < 0))
507
throw new ArgumentOutOfRangeException("destinationIndex");
509
if ((sourceIndex >= array.Length) || (sourceIndex < 0))
511
throw new ArgumentOutOfRangeException("sourceIndex");
513
if ((destinationIndex + length > this.length) ||
514
(sourceIndex + length > array.Length) ||
517
throw new ArgumentOutOfRangeException("length");
520
if (isOneBit || isFourBit)
522
for (int i = 0; i != length; i++)
524
SetValueInternal(array[sourceIndex++], destinationIndex++);
529
GCHandle handle = GCHandle.Alloc(array, GCHandleType.Pinned);
530
byte* src = (byte*)Marshal.UnsafeAddrOfPinnedArrayElement(array, sourceIndex);
531
CopyMemory(baseAddress + (size * destinationIndex), src, size * length);
537
/// Returns the represented block of memory as an array of <see cref="Byte"/>.
539
/// <returns>The represented block of memory.</returns>
540
public byte[] ToByteArray()
546
result = new byte[(length + 7) / 8];
550
result = new byte[(length + 3) / 4];
554
result = new byte[size * length];
556
fixed (byte* dst = result)
558
CopyMemory(dst, baseAddress, result.Length);
564
/// Gets or sets the value at the specified position in the array.
566
/// <param name="index">A 32-bit integer that represents the position
567
/// of the array element to get.</param>
568
/// <returns>The value at the specified position in the array.</returns>
569
/// <exception cref="ArgumentOutOfRangeException">
570
/// <paramref name="index"/> is outside the range of valid indexes
571
/// for the unmanaged array.</exception>
572
public T this[int index]
576
return GetValue(index);
580
SetValue(value, index);
585
/// Gets or sets the values of the unmanaged array.
591
return GetValues(0, length);
597
throw new ArgumentNullException("value");
599
if (value.Length != length)
601
throw new ArgumentOutOfRangeException("value.Lengt");
608
/// Gets the length of the unmanaged array.
620
/// Gets the base address of the represented memory block.
622
public IntPtr BaseAddress
627
return new IntPtr(baseAddress);
632
/// Creates a shallow copy of the <see cref="MemoryArray<T>"/>.
634
/// <returns>A shallow copy of the <see cref="MemoryArray<T>"/>.</returns>
635
public object Clone()
638
return new MemoryArray<T>(baseAddress, length);
642
/// Gets a 32-bit integer that represents the total number of elements
643
/// in the <see cref="MemoryArray<T>"/>.
647
get { EnsureNotDisposed(); return length; }
651
/// Gets a value indicating whether access to the <see cref="MemoryArray<T>"/>
652
/// is synchronized (thread safe).
654
public bool IsSynchronized
656
get { EnsureNotDisposed(); return false; }
660
/// Gets an object that can be used to synchronize access to the <see cref="MemoryArray<T>"/>.
662
public object SyncRoot
667
if (syncRoot == null)
669
System.Threading.Interlocked.CompareExchange(ref syncRoot, new object(), null);
676
/// Retrieves an object that can iterate through the individual
677
/// elements in this <see cref="MemoryArray<T>"/>.
679
/// <returns>An <see cref="IEnumerator"/> for the <see cref="MemoryArray<T>"/>.</returns>
680
public IEnumerator GetEnumerator()
683
T[] values = GetValues(0, length);
684
for (int i = 0; i != values.Length; i++)
686
yield return values[i];
691
/// Retrieves an object that can iterate through the individual
692
/// elements in this <see cref="MemoryArray<T>"/>.
694
/// <returns>An <see cref="IEnumerator<T>"/> for the <see cref="MemoryArray<T>"/>.</returns>
695
IEnumerator<T> IEnumerable<T>.GetEnumerator()
698
T[] values = GetValues(0, length);
699
for (int i = 0; i != values.Length; i++)
701
yield return values[i];
706
/// Releases all ressources.
708
public void Dispose()
711
GC.SuppressFinalize(this);
715
/// Releases allocated handles associated with this instance.
717
/// <param name="disposing"><b>true</b> to release managed resources.</param>
718
protected virtual void Dispose(bool disposing)
720
if (baseAddress != null)
722
if (handle.IsAllocated)
732
/// Throws an <see cref="ObjectDisposedException"/> if
733
/// this instance is disposed.
735
protected virtual void EnsureNotDisposed()
737
if (baseAddress == null)
738
throw new ObjectDisposedException("This instance is disposed.");
742
/// Tests whether the specified <see cref="MemoryArray<T>"/> structure is equivalent to this
743
/// <see cref="MemoryArray<T>"/> structure.
745
/// <param name="obj">The structure to test.</param>
746
/// <returns><b>true</b> if <paramref name="obj"/> is a <see cref="MemoryArray<T>"/>
747
/// instance equivalent to this <see cref="MemoryArray<T>"/> structure; otherwise,
748
/// <b>false</b>.</returns>
749
public override bool Equals(object obj)
752
return ((obj is MemoryArray<T>) && Equals((MemoryArray<T>)obj));
756
/// Tests whether the specified <see cref="MemoryArray<T>"/> structure is equivalent to this
757
/// <see cref="MemoryArray<T>"/> structure.
759
/// <param name="other">The structure to test.</param>
760
/// <returns><b>true</b> if <paramref name="other"/> is equivalent to this
761
/// <see cref="MemoryArray<T>"/> structure; otherwise,
762
/// <b>false</b>.</returns>
763
public bool Equals(MemoryArray<T> other)
766
return ((this.baseAddress == other.baseAddress) && (this.length == other.length));
770
/// Serves as a hash function for a particular type.
772
/// <returns>A hash code for the current <see cref="MemoryArray<T>"/>.</returns>
773
public override int GetHashCode()
776
return (int)baseAddress ^ length;
780
/// Copies a block of memory from one location to another.
782
/// <param name="dest">Pointer to the starting address of the copy destination.</param>
783
/// <param name="src">Pointer to the starting address of the block of memory to be copied.</param>
784
/// <param name="len">Size of the block of memory to copy, in bytes.</param>
785
protected static unsafe void CopyMemory(byte* dest, byte* src, int len)
791
*((int*)dest) = *((int*)src);
792
*((int*)(dest + 4)) = *((int*)(src + 4));
793
*((int*)(dest + 8)) = *((int*)(src + 8));
794
*((int*)(dest + 12)) = *((int*)(src + 12));
798
while ((len -= 0x10) >= 0x10);
804
*((int*)dest) = *((int*)src);
805
*((int*)(dest + 4)) = *((int*)(src + 4));
811
*((int*)dest) = *((int*)src);
817
*((short*)dest) = *((short*)src);
b'\\ No newline at end of file'