NativeArray.cs 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. using System;
  2. using System.Runtime.CompilerServices;
  3. using System.Runtime.InteropServices;
  4. namespace Ryujinx.Graphics.Vulkan
  5. {
  6. unsafe class NativeArray<T> : IDisposable where T : unmanaged
  7. {
  8. public T* Pointer { get; private set; }
  9. public int Length { get; }
  10. public ref T this[int index]
  11. {
  12. get => ref Pointer[Checked(index)];
  13. }
  14. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  15. private int Checked(int index)
  16. {
  17. if ((uint)index >= (uint)Length)
  18. {
  19. throw new IndexOutOfRangeException();
  20. }
  21. return index;
  22. }
  23. public NativeArray(int length)
  24. {
  25. Pointer = (T*)Marshal.AllocHGlobal(checked(length * Unsafe.SizeOf<T>()));
  26. Length = length;
  27. }
  28. public Span<T> ToSpan()
  29. {
  30. return new Span<T>(Pointer, Length);
  31. }
  32. public void Dispose()
  33. {
  34. Marshal.FreeHGlobal((IntPtr)Pointer);
  35. Pointer = null;
  36. }
  37. }
  38. }