Re: Safe handles and Marshal class
Peter Ritchie <[email protected]> Tue, 12 Feb 2008 16:10:30 -0500
| Newsgroups | gmane.comp.windows.devel.dotnet.clr |
|---|---|
| Message-ID | <LISTSERV%[email protected]> |
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