Ptr.cs 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. using System;
  2. using System.Diagnostics.CodeAnalysis;
  3. using System.Runtime.CompilerServices;
  4. namespace Ryujinx.Common.Memory
  5. {
  6. /// <summary>
  7. /// Represents a pointer to an unmanaged resource.
  8. /// </summary>
  9. /// <typeparam name="T">Type of the unmanaged resource</typeparam>
  10. public unsafe struct Ptr<T> : IEquatable<Ptr<T>> where T : unmanaged
  11. {
  12. private IntPtr _ptr;
  13. /// <summary>
  14. /// Null pointer.
  15. /// </summary>
  16. public static Ptr<T> Null => new Ptr<T>() { _ptr = IntPtr.Zero };
  17. /// <summary>
  18. /// True if the pointer is null, false otherwise.
  19. /// </summary>
  20. public bool IsNull => _ptr == IntPtr.Zero;
  21. /// <summary>
  22. /// Gets a reference to the value.
  23. /// </summary>
  24. public ref T Value => ref Unsafe.AsRef<T>((void*)_ptr);
  25. /// <summary>
  26. /// Creates a new pointer to an unmanaged resource.
  27. /// </summary>
  28. /// <remarks>
  29. /// For data on the heap, proper pinning is necessary during
  30. /// use. Failure to do so will result in memory corruption and crashes.
  31. /// </remarks>
  32. /// <param name="value">Reference to the unmanaged resource</param>
  33. public Ptr(ref T value)
  34. {
  35. _ptr = (IntPtr)Unsafe.AsPointer(ref value);
  36. }
  37. public override bool Equals(object obj)
  38. {
  39. return obj is Ptr<T> other && Equals(other);
  40. }
  41. public bool Equals([AllowNull] Ptr<T> other)
  42. {
  43. return _ptr == other._ptr;
  44. }
  45. public override int GetHashCode()
  46. {
  47. return _ptr.GetHashCode();
  48. }
  49. public static bool operator ==(Ptr<T> left, Ptr<T> right)
  50. {
  51. return left.Equals(right);
  52. }
  53. public static bool operator !=(Ptr<T> left, Ptr<T> right)
  54. {
  55. return !(left == right);
  56. }
  57. }
  58. }