釋放以前從進程的非托管內存中分配的內存。
命名空間: System.Runtime.InteropServices
程序集: mscorlib(位於 mscorlib.dll)
下面的示例演示如何將托管的內容轉換 String 類寫入非托管內存,並因而釋放非托管內存完成。
using System; using System.Runtime.InteropServices; class MainFunction { static void Main() { Console.WriteLine("\nStringToGlobalAnsi\n"); // Create a managed string. String managedString = "I am a managed String"; Console.WriteLine("1) managedString = " + managedString ); // Marshal the managed string to unmanaged memory. IntPtr stringPointer = (IntPtr)Marshal.StringToHGlobalAnsi(managedString); Console.WriteLine("2) stringPointer = {0}", stringPointer ); // Get the string back from unmanaged memory String RetrievedString = Marshal.PtrToStringAnsi( stringPointer); Console.WriteLine("3) Retrieved from unmanaged memory = " + RetrievedString ); // Always free the unmanaged string. Marshal.FreeHGlobal(stringPointer); // IntPtr handle value is still the same: Console.WriteLine("4) stringPointer = " + stringPointer ); // However, it contains no data after being freed: String RetrievedString2 = Marshal.PtrToStringAnsi( stringPointer); Console.WriteLine("5) RetrievedString2 = " + RetrievedString2 ); } }
https://msdn.microsoft.com/zh-cn/library/system.runtime.interopservices.marshal.freehglobal(v=vs.110).aspx