[quoted text, click to view] john conwell wrote:
> I'm using Marshal::StructureToPtr to well...marshal a struct over to
> unmanaged memory and get its pointer.
>
> Which method should I use to destroy the memory the pointer represents?
Because Marshal.StructureToPtr() requires already allocated memory, you
should use the counterpart of whatever method you used to allocate it. If
it's statically allocated, don't free it. If you used GlobalAlloc(), use
GlobalFree(). If new[], use delete, if Marshal.AllocHGlobal(), use
Marshal.FreeHGlobal(), if Marshal.AllocCoTaskMem() use
Marshal.FreeCoTaskMem(), etc.
[quoted text, click to view] > Marshal.DestroyStructure or Marshal.FreehGlobal? Does it matter?
>
They have completely different goals. Marshal.DestroyStructure() is for
freeing memory allocated by reference fields of the struct. In particular,
it calls SysFreeString() for any string fields marshalled as BSTR, since
separate memory needs to be allocated for them that must be freed before the
structure itself is freed.
If you have such fields, you need to call .DestroyStructure() before freeing
the struct itself. You can do that with .FreeHGlobal(), if the memory was
allocated with .AllocHGlobal().
--