开发者

Free managed memory allocation from unmanaged code

开发者 https://www.devze.com 2023-03-20 08:08 出处:网络
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.

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号