The Labs \ Source Viewer \ SSCLI \ Microsoft.Win32.SafeHandles \ SafeNativeMemoryHandle

  1. // ==++==
  2. //
  3. //
  4. // Copyright (c) 2006 Microsoft Corporation. All rights reserved.
  5. //
  6. // The use and distribution terms for this software are contained in the file
  7. // named license.txt, which can be found in the root of this distribution.
  8. // By using this software in any fashion, you are agreeing to be bound by the
  9. // terms of this license.
  10. //
  11. // You must not remove this notice, or any other, from this software.
  12. //
  13. //
  14. // ==--==
  15. /*============================================================
  16. **
  17. ** Class:  SafeMemoryHandle
  18. **
  19. **
  20. ** This class is wrapper for native (unsafe) memory pointer 
  21. ** allocated using Marshal.AllocHGlobal.
  22. **
  23. **
  24. ===========================================================*/
  25. using System;
  26. using System.Security;
  27. using System.Security.Permissions;
  28. using System.Runtime.InteropServices;
  29. using System.Runtime.CompilerServices;
  30. using System.Runtime.ConstrainedExecution;
  31. using Microsoft.Win32;
  32. using Microsoft.Win32.SafeHandles;
  33. namespace Microsoft.Win32.SafeHandles
  34. {
  35.     [SuppressUnmanagedCodeSecurityAttribute()]
  36.     internal sealed class SafeNativeMemoryHandle : SafeHandleZeroOrMinusOneIsInvalid
  37.     {
  38.         [SecurityPermission(SecurityAction.LinkDemand, UnmanagedCode = true)]
  39.         internal SafeNativeMemoryHandle() : base(true)
  40.         {
  41.         }
  42.        
  43.         [SecurityPermission(SecurityAction.LinkDemand, UnmanagedCode = true)]
  44.         internal SafeNativeMemoryHandle(IntPtr handle, bool ownsHandle) : base(ownsHandle)
  45.         {
  46.             SetHandle(handle);
  47.         }
  48.        
  49.         protected override bool ReleaseHandle()
  50.         {
  51.             if (handle != IntPtr.Zero) {
  52.                 Marshal.FreeHGlobal(handle);
  53.                 handle = IntPtr.Zero;
  54.                 return true;
  55.             }
  56.             return false;
  57.         }
  58.     }
  59. }

Developer Fusion