PinnedGCHandle.cs 895 B

123456789101112131415161718192021222324252627282930313233343536373839
  1. #region Copyright and License
  2. /*
  3. This file is part of FFTW.NET, a wrapper around the FFTW library for the .NET framework.
  4. Copyright (C) 2017 Tobias Meyer
  5. License: Microsoft Reciprocal License (MS-RL)
  6. */
  7. #endregion
  8. using System;
  9. using System.Runtime.InteropServices;
  10. namespace FFTW.NET
  11. {
  12. public struct PinnedGCHandle : IDisposable
  13. {
  14. GCHandle _handle;
  15. PinnedGCHandle(GCHandle handle)
  16. {
  17. _handle = handle;
  18. }
  19. public static PinnedGCHandle Pin(object obj) => new PinnedGCHandle(GCHandle.Alloc(obj, GCHandleType.Pinned));
  20. public void Free() => _handle.Free();
  21. void IDisposable.Dispose()
  22. {
  23. if (_handle.IsAllocated)
  24. _handle.Free();
  25. }
  26. public override string ToString() => _handle.ToString() ?? string.Empty;
  27. public IntPtr Pointer => _handle.AddrOfPinnedObject();
  28. public bool IsAllocated => _handle.IsAllocated;
  29. public object? Target => _handle.Target;
  30. }
  31. }