mirror of
https://github.com/cyanfish/naps2.git
synced 2024-10-05 03:47:10 +03:00
94 lines
2.9 KiB
C#
94 lines
2.9 KiB
C#
using System;
|
|
using System.Collections.Generic;
|
|
using System.Linq;
|
|
using System.Runtime.InteropServices;
|
|
|
|
namespace NAPS2
|
|
{
|
|
public class UnmanagedArray<T> : UnmanagedBase<T[]>
|
|
{
|
|
public UnmanagedArray(IEnumerable<T> array)
|
|
{
|
|
ElementSize = Marshal.SizeOf(typeof(T));
|
|
if (array != null)
|
|
{
|
|
var arrayVal = array as IList<T> ?? array.ToList();
|
|
|
|
Length = arrayVal.Count;
|
|
Size = ElementSize * Length;
|
|
Pointer = Marshal.AllocHGlobal(Size);
|
|
|
|
// Populate the contents of the unmanaged array
|
|
for (int i = 0; i < Length; ++i)
|
|
{
|
|
Marshal.StructureToPtr(arrayVal[i], this[i], false);
|
|
}
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// Gets the size of each element in the unmanaged array in bytes.
|
|
/// </summary>
|
|
public int ElementSize { get; private set; }
|
|
|
|
/// <summary>
|
|
/// Gets the number of elements in the unmanaged array.
|
|
/// </summary>
|
|
public int Length { get; private set; }
|
|
|
|
/// <summary>
|
|
/// Gets the pointer offset to access the element of the unmanaged array at the given index.
|
|
/// </summary>
|
|
/// <param name="index">The index of the element to access.</param>
|
|
/// <returns>The offset, relative to the Pointer.</returns>
|
|
public int Offset(int index)
|
|
{
|
|
if (index < 0 || index >= Length)
|
|
{
|
|
throw new ArgumentOutOfRangeException("index");
|
|
}
|
|
return index * ElementSize;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Gets the pointer to the element of the unmanaged array at the given index.
|
|
/// </summary>
|
|
/// <param name="index">The index of the item to access.</param>
|
|
/// <returns>The pointer to the element.</returns>
|
|
public IntPtr PointerWithOffset(int index)
|
|
{
|
|
return Pointer + Offset(index);
|
|
}
|
|
|
|
protected override T[] GetValue()
|
|
{
|
|
var result = new T[Length];
|
|
for (int i = 0; i < Length; ++i)
|
|
{
|
|
result[i] = (T)Marshal.PtrToStructure(this[i], typeof(T));
|
|
}
|
|
return result;
|
|
}
|
|
|
|
protected override void DestroyStructures()
|
|
{
|
|
for (int i = 0; i < Length; ++i)
|
|
{
|
|
Marshal.DestroyStructure(this[i], typeof(T));
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// Gets the pointer to the element of the unmanaged array at the given index.
|
|
/// </summary>
|
|
/// <param name="index">The index of the item to access.</param>
|
|
/// <returns>The pointer to the element.</returns>
|
|
public IntPtr this[int index]
|
|
{
|
|
get
|
|
{
|
|
return PointerWithOffset(index);
|
|
}
|
|
}
|
|
}
|
|
} |