且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Marshal.FreeHGlobal 方法 (IntPtr)

更新时间:2022-09-06 18:11:06

释放以前从进程的非托管内存中分配的内存。

命名空间: System.Runtime.InteropServices
程序集: mscorlib(位于 mscorlib.dll)

下面的示例演示如何将托管的内容转换 String 类写入非托管内存,并因而释放非托管内存完成。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
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
本文转自jiahuafu博客园博客,原文链接http://www.cnblogs.com/jiahuafu/p/6893931.html如需转载请自行联系原作者

jiahuafu