Safe IntPtr handle

EDN Admin

Well-known member
Joined
Aug 7, 2010
Messages
12,794
Location
In the Machine
I wrote the class which is supposed to be used as IntPtr wrapper. It should keep result of Marshal.AllocHGlobal operation, and calls Marshal.FreeHGlobal when instance is disposed or finalized. Class is tested and appears to work properly in different situations.
I want to ask C# gurus to take a look at this class and post opinions about it: C# programming style, safety etc. - something that I possibly missed.
 
   /// <summary>
    /// IntPtr wrapper which can be used as result of
    /// Marshal.AllocHGlobal operation.
    /// Call Marshal.FreeHGlobal when disposed or finalized.
    /// </summary>
    class HGlobalSafeHandle : SafeHandle
    {
        /// <summary>
        /// Creates new instance with given IntPtr value
        /// </summary>
        public HGlobalSafeHandle(IntPtr ptr) : base(ptr, true)
        {
        }
        /// <summary>
        /// Creates new instance with zero IntPtr
        /// </summary>
        public HGlobalSafeHandle() : base(IntPtr.Zero, true)
        {
        }
        /// <summary>
        /// Creates new instance which allocates unmanaged memory of given size
      /// Can throw OutOfMemoryException - is this bad, any idea how to do this better?
        /// </summary>
        public HGlobalSafeHandle(int size) :
            base(Marshal.AllocHGlobal(size), true)
        {
        }

        /// <summary>
        /// Allows to assign IntPtr to HGlobalSafeHandle
        /// </summary>
        public static implicit operator HGlobalSafeHandle(IntPtr ptr)
        {
            return new HGlobalSafeHandle(ptr);
        }
        /// <summary>
        /// Allows to use HGlobalSafeHandle as IntPtr
        /// </summary>
        public static implicit operator IntPtr(HGlobalSafeHandle h)
        {
            return h.handle;
        }
        /// <summary>
        /// Called when object is disposed or finalized.
        /// </summary>
        override protected bool ReleaseHandle()
        {
            Marshal.FreeHGlobal(handle);
            return true;
        }
        /// <summary>
        /// Defines invalid (null) handle value.
        /// </summary>
        public override bool IsInvalid
        {
            get
            {
                return (handle == IntPtr.Zero);
            }
        }
    }


View the full article
 

Similar threads

S
Replies
0
Views
108
Stan Huang at Taiwan
S
A
Replies
0
Views
143
Afshan Gul
A
R
Replies
0
Views
164
RGwolf
R
Back
Top