Advertisement
MaksNew

Untitled

Jan 1st, 2023 (edited)
1,412
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.62 KB | None | 0 0
  1. using System.Runtime.InteropServices;
  2.  
  3. namespace T4
  4. {
  5.     public class NativeBuffer : IDisposable
  6.     {
  7.         private IntPtr hglobal;
  8.         private bool disposed = false;
  9.         public IntPtr Handle { get { return hglobal; } }
  10.  
  11.         public void Dispose()
  12.         {
  13.             Dispose(true);
  14.             GC.SuppressFinalize(this);
  15.         }
  16.  
  17.         protected virtual void Dispose(bool disposing)
  18.         {
  19.             if (disposed) return;
  20.             if (disposing)
  21.             {
  22.                 try
  23.                 {
  24.                     if (hglobal != IntPtr.Zero)
  25.                         Marshal.FreeHGlobal(hglobal);
  26.                 }
  27.                 catch
  28.                 {
  29.                 }
  30.             }
  31.             //here clean uncontrol
  32.             disposed = true;
  33.         }
  34.  
  35.         ~NativeBuffer()
  36.         {
  37.             Dispose(false);
  38.         }
  39.  
  40.         public bool AllocHGlobal(int cb)
  41.         {
  42.             try
  43.             {
  44.                 if (hglobal == IntPtr.Zero)
  45.                     hglobal = Marshal.AllocHGlobal(cb);
  46.                 return true;
  47.             }
  48.             catch
  49.             {
  50.                 return false;
  51.             }
  52.         }
  53.  
  54.         public bool FreeHGlobal()
  55.         {
  56.             try
  57.             {
  58.                 if (hglobal != IntPtr.Zero)
  59.                     Marshal.FreeHGlobal(hglobal);
  60.                 return true;
  61.             }
  62.             catch
  63.             {
  64.                 return false;
  65.             }
  66.         }
  67.  
  68.         public bool IsAllocked()
  69.         {
  70.             return hglobal != IntPtr.Zero;
  71.         }
  72.     }
  73. }
  74.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement