Free managed memory allocation from unmanaged code
I'd like to do Marshal.AllocHGlobal
in managed code, fill it with data, and pass that memory block to unmanaged (C++) code that will then be responsible for freeing it.
Under the hood, Marshal.AllocHGlobal
calls LocalAlloc
(and, I'm guessing, LocalLock
). But in order for the unmanaged code to call LocalFree, it needs the HLOCAL returned by LocalAlloc
, which Marshal.AllocHGlobal
doesn't provide.
I'm not necessarily restricted to using AllocHGlobal
; the high level goal is to开发者_如何学Python let the managed code allocate memory that the unmanaged code and then read and free.
This is not a handle, not since Windows version 3. Calling LocalFree() on the pointer is fine, as the Windows SDK article shows in its example. Marshal.AllocCoTaskMem and CoTaskMemFree() are the better mouse trap here.
精彩评论