For example:
[DllImport(...)]
public static extern void MyFunc(
[MarshalAs(UnmanagedType.LPWStr)]
out String myString);
If native code allocated myString using CoTaskMemAlloc, is it freed
automatically here? What if the string was allocated using HeapAlloc -- how
would it know which heap in this case? Does it support
LocalAlloc/GlobalAlloc? I couldn't find any MSDN resources on automatic
releasing of allocations during interop.
Thanks
Michael Phillips, Jr. - 29 Jun 2006 00:20 GMT
You must read the documentation for the Library and use the appropriate
method to deallocate memory.
If the library allocates memory for the string with CoTaskMemAlloc, then you
must free the memory with Marshal.FreeCoTaskMem().
This means you must marshal as an IntPtr to deallocate the memory with the
appropriate Marshal deallocator method.
The Marshaler has no way of knowing how the library allocated memory for the
string that is passed to you. Memory leaks are possible if you do not
deallocate the unmanaged memory that was allocated for the string.
> For example:
>
[quoted text clipped - 10 lines]
>
> Thanks
lgs.lgs - 29 Jun 2006 01:38 GMT
You might find this to be of use:
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpguide/html/cp
conmemorymanagement.asp
Bob - 29 Jun 2006 02:52 GMT
Thanks, this answered my question. Basically, it always attempts to use
CoTaskMemFree and if I don't want that, I need to use IntPtr and marshal
manually.
> You might find this to be of use:
>
> http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpguide/html/cp
conmemorymanagement.asp