How do I free memory allocated inside unmanaged DLL?
-
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