Re: Safe handles and Marshal class
Alex Ivanoff <[email protected]> Tue, 12 Feb 2008 22:57:34 -0600
| Newsgroups | gmane.comp.windows.devel.dotnet.clr |
|---|---|
| Message-ID | <[email protected]> |
Two things: 1. You do not need to declare handle, SafeHandle class has protected member handle. 2. You are exposing handle publicly which is not good. -----Original Message----- From: Discussion of development on the .NET platform using any managed language [mailto:[email protected]] On Behalf Of Peter Ritchie Sent: Tuesday, February 12, 2008 15:11 To: [email protected] Subject: Re: [DOTNET-CLR] Safe handles and Marshal class For some reason I was thinking native memory with Marshal and Marshal.AllocCoTaskMem--which has no "handle"... I haven't seen anything like that for native global heap handles; but, off the top of my head, this might be useful: /// <summary> /// Class to encapsulate a native global memory handle /// </summary> /// <revisionHistory><revision name="Peter Ritchie" date="12-feb- 08">Created.</revision></revisionHistory> public class SafeGlobalMemoryHandle : SafeHandle { private IntPtr handle; public SafeGlobalMemoryHandle(int size) { handle = Marshal.AllocHGlobal(); } #region SafeHandle overrides protected override bool ReleaseHandle() { IntPtr toFree = System.Threading.Interlocked.Exchange(ref handle, IntPtr.Zero); Marshal.FreeHGlobal(toFree); } public override bool IsInvalid { get { return handle != IntPtr.Zero; } } #endregion SafeHandle overrides /// <summary> /// implicit operator so a SafeGloblaMemoryHandle may be uses in place of an IntPtr /// </summary> /// <param name="safeGlobalMemoryHandle">SafeGlobalMemoryHandle in question</param> /// <returns>IntPtr representing the native global memory handle</returns> /// <remarks>Use with caution, not all IntPtr's are global memory handles.</remarks> public static implicit operator IntPtr (SafeGlobalMemoryHandle safeGlobalMemoryHandle) { return safeGlobalMemoryHandle.handle; } } =================================== This list is hosted by DevelopMentorĀ® http://www.develop.com View archives and manage your subscription(s) at http://discuss.develop.com