Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Code Project
  1. Home
  2. General Programming
  3. C#
  4. How do I free memory allocated inside unmanaged DLL?

How do I free memory allocated inside unmanaged DLL?

Scheduled Pinned Locked Moved C#
questioncsharpc++performancehelp
1 Posts 1 Posters 0 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • K Offline
    K Offline
    Koushik Biswas
    wrote on last edited by
    #1

    OK - I want to keep the question short & quick. Please help me. Step 1: I write an unmanaged DLL in C++. Here is the exported function: SAMPLEDLL_API void StringAsOUT_AllocatedInDll( char ** szParam ) { *szParam = new char [ 128 ]; strcpy( *szParam, "Please free my memory after using me!" ); } Step 2: I write a C# managed EXE to use this DLL class Imports { [DllImport("SampleDLL.dll")] public static extern void StringAsOUT_AllocatedInDll( ref int szParam ); ... } ... Imports impObj = new Imports(); int iAddressOfANSIString = 0; impObj.StringAsOUT_AllocatedInDll( ref iAddressOfANSIString ); string strOUTPUTFromUnmanagedDll = Marshal.PtrToStringAnsi( ( IntPtr ) iAddressOfANSIString ); Console.WriteLine( "Value of strOUTPUTFromUnmanagedDll = {0}", strOUTPUTFromUnmanagedDll ); ... Question: The code works. It does give console output "Value of strOUTPUTFromUnmanagedDll = Please free my memory after using me!" But isn't there a memory leak? How do I free the memory allocated by new[] inside the unmanaged DLL? All the Marshal class helps artciles always refer to how to free an unmanaged memory block when it is allocated from .NET code. But here it is allocated by unamanaged code. If anybody can please help me with this, I will be grateful. Thank you! Koushik Biswas

    1 Reply Last reply
    0
    Reply
    • Reply as topic
    Log in to reply
    • Oldest to Newest
    • Newest to Oldest
    • Most Votes


    • Login

    • Don't have an account? Register

    • Login or register to search.
    • First post
      Last post
    0
    • Categories
    • Recent
    • Tags
    • Popular
    • World
    • Users
    • Groups