Marshal.FreeHGlobal 方法 (IntPtr)


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

命名空间:   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


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM