释放以前从进程的非托管内存中分配的内存。
命名空间:
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 );