From the MSDN documentation of Marshal.AllocHGlobal
:
AllocHGlobal is one of two memory allocation methods in the Marshal class. This method exposes the Win32 LocalAlloc function from Kernel32.dll.
Considering there's a GlobalAlloc API which allocates memory on the global heap, rather than the local heap, isn't this method's name rather misleading?
Was there a reason for naming it AllocHGlobal
, rather than AllocHLocal
?
Update: Simon points out in the comments that there's no such thing as a global heap in Windows any more, and the GlobalAlloc
and LocalAlloc
APIs remained for legacy purposes only. These days, the GlobalAlloc
API is nothing morethan a wrapper for LocalAlloc
.
This explains why the API doesn't call GlobalAlloc
at all, but it doesn't explain why the API was named AllocHGlobal
when it doesn't (can't) use a global heap, nor does it even call GlobalAlloc
. The naming cannot possibly be for legacy reasons, because it wasn't introduced until .NET 2.0, way after 16-bit support was dropped. So, the question remains: why is Marshal.AllocHGlobal
so misleadingly named?
Suppose you're doing data transfer between apps using drag and drop or over the clipboard. To populate the STGMEDIUM
structure you need an HGLOBAL
. So you call AllocHGlobal
. Hence the name.
The main use for this function is to interop with APIs that want an HGLOBAL
. It would be confusing if it was called anything else because when you wanted an HGLOBAL
you'd have to find some documentation to tell you that AllocAnythingElse
produced a value you could use as an HGLOBAL
.