Re: Safe handles and Marshal class

Peter Ritchie <[email protected]> Wed, 13 Feb 2008 16:04:51 -0500
Newsgroups gmane.comp.windows.devel.dotnet.clr
Message-ID <LISTSERV%[email protected]>
Allocating memory with Marshal.AllocHGlobal is but one way of
allocating "native memory".  You usually use this when you need to pass
blobs of memory to Win32 code (like the clipboard or printing).  It's a
heavy-weight allocation (i.e. there's a few bytes uses for administration
for each allocation).  It allocates memory on the local heap (not the
global heap, as the name suggests), there's also global heap allocation
and higher-level allocations like CoAllocTaskMem (managed via
Marshal.AllocCoTaskMem) which is what the Marshaller uses to allocate
memory during PInvoke.  If you plan on allocating memory in a managed
layer to be freed in a native later, AllocCoTaskMem is the one to use.

There's the assumption that native memory is going to be passed via
PInvoke to native code, in which case automatic "garbage collection" of
the memory is often not a good thing.  So, even if you wrapped it with a
SafeHandle-derived class you'd likely have to wrap that with a HandleRef.

===================================
This list is hosted by DevelopMentorĀ®  http://www.develop.com

View archives and manage your subscription(s) at http://discuss.develop.com