PinnedObject.cs 868 B

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. using System;
  2. using System.Runtime.InteropServices;
  3. namespace UTJ.FbxExporter
  4. {
  5. public class PinnedObject<T> : IDisposable
  6. {
  7. public PinnedObject(T data)
  8. {
  9. this.m_data = data;
  10. this.m_gch = GCHandle.Alloc(this.m_data, GCHandleType.Pinned);
  11. }
  12. public T Object
  13. {
  14. get
  15. {
  16. return this.m_data;
  17. }
  18. }
  19. public IntPtr Pointer
  20. {
  21. get
  22. {
  23. return this.m_gch.AddrOfPinnedObject();
  24. }
  25. }
  26. public void Dispose()
  27. {
  28. this.Dispose(true);
  29. GC.SuppressFinalize(this);
  30. }
  31. protected virtual void Dispose(bool disposing)
  32. {
  33. if (disposing && this.m_gch.IsAllocated)
  34. {
  35. this.m_gch.Free();
  36. }
  37. }
  38. public static implicit operator IntPtr(PinnedObject<T> v)
  39. {
  40. return v.Pointer;
  41. }
  42. public static implicit operator T(PinnedObject<T> v)
  43. {
  44. return v.Object;
  45. }
  46. private T m_data;
  47. private GCHandle m_gch;
  48. }
  49. }