Home | Contact Us | FAQ | Search & Site Map | Link to Us
Sign In | Join | Other 45 Sites in Network
HomeAnnouncementsFree MagazinesWhite PapersSubmit Content
Discussion GroupsASP.NETWindows FormsLanguages.NET FrameworkVisual Studio.NET
Articles.NET FrameworkASP.NETToolsWindows Forms
.NET DirectoryOpen Source ProjectsUser GroupsWeb Resources
Related Topics
Visual Basic 6SQL ServerMS AccessOther DB ProductsMS Server ProductsMore Topics ...

.NET Forum / .NET Framework / Interop / June 2006

Tip: Looking for answers? Try searching our database.

Does interop automatically free strings allocated in unmanaged code?

Thread view: 
Enable EMail Alerts  Start New Thread
Thread rating: 
Bob - 28 Jun 2006 22:56 GMT
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

Free Magazines

Get these publications absolutely FREE for up to 12 months. There are no hidden fees and no obligation. Simply choose a title, complete the application form and submit it. Read more ...

Oracle MagazineNetwork ComputingComputer WorldBio-IT WorldeWeekInformation WeekInfosecurity
 
Sign In
Join
My Latest Posts
My Monitored Threads
My Blog
My Photo Gallery
My Profile
My Homepage

Start New Thread
Enable EMail Alerts
Rate this Thread



©2008 Advenet LLC   Privacy Policy - Terms of Use
This website includes both content owned or controlled by Advenet as well as content owned or controlled by third parties.