Marshal.FreeHGlobal(IntPtr) Método

Definição

Liberta a memória previamente alocada da memória não gerida do processo.

public:
 static void FreeHGlobal(IntPtr hglobal);
[System.Security.SecurityCritical]
public static void FreeHGlobal(IntPtr hglobal);
public static void FreeHGlobal(IntPtr hglobal);
[<System.Security.SecurityCritical>]
static member FreeHGlobal : nativeint -> unit
static member FreeHGlobal : nativeint -> unit
Public Shared Sub FreeHGlobal (hglobal As IntPtr)

Parâmetros

hglobal
IntPtr

nativeint

O handle devolvido pela chamada correspondente original para AllocHGlobal(IntPtr).

Atributos

Exemplos

O exemplo seguinte demonstra chamar o FreeHGlobal método. Este exemplo de código faz parte de um exemplo maior fornecido para a Marshal classe.

// Demonstrate how to call GlobalAlloc and
// GlobalFree using the Marshal class.
IntPtr hglobal = Marshal::AllocHGlobal(100);
Marshal::FreeHGlobal(hglobal);
// Demonstrate how to call GlobalAlloc and
// GlobalFree using the Marshal class.
IntPtr hglobal = Marshal.AllocHGlobal(100);
Marshal.FreeHGlobal(hglobal);
' Demonstrate how to call GlobalAlloc and
' GlobalFree using the Marshal class.
Dim hglobal As IntPtr = Marshal.AllocHGlobal(100)
Marshal.FreeHGlobal(hglobal)

O exemplo seguinte demonstra como converter o conteúdo de uma classe gerida String para memória não gerida e depois descartar a memória não gerida quando terminar.

using namespace System;
using namespace System::Runtime::InteropServices;

#include <iostream>                                                 // for printf


int main()
{
    // Create a managed string.
    String^ managedString = "Hello unmanaged world (from the managed world).";

    // Marshal the managed string to unmanaged memory.
    char* stringPointer = (char*) Marshal::StringToHGlobalAnsi(managedString ).ToPointer();

    printf("stringPointer = %s\n", stringPointer);

    // Always free the unmanaged string.
    Marshal::FreeHGlobal(IntPtr(stringPointer));

    return 0;
}
using System;
using System.Runtime.InteropServices;
using System.Threading;

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, the data may be cleared after the memory is freed, depending on whether the memory allocated to stringPointer
        // has been reclaimed or not. Uncommenting the following line (Thread.Sleep(1000)) increases the likelihood of the memory being reclaimed.
        // Thread.Sleep(1000);
        String RetrievedString2 = Marshal.PtrToStringAnsi(stringPointer);
        Console.WriteLine("5) RetrievedString2 = " + RetrievedString2);
    }
}

Observações

Importante

Este alocador de memória nativo é uma API legada que deve ser usada exclusivamente quando solicitada por APIs Win32 específicas na plataforma Windows. Ao direcionar .NET 6 ou posteriores, use a classe NativeMemory em todas as plataformas para alocar memória nativa. Ao direcionar .NET Framework, use AllocCoTaskMem em todas as plataformas para alocar memória nativa.

Pode usar FreeHGlobal para libertar qualquer memória do heap global alocado por AllocHGlobal, ReAllocHGlobal, ou qualquer método equivalente de API não gerida. Se o hglobal parâmetro for IntPtr.Zero o método não faz nada.

FreeHGlobal expõe a função LocalFree de Kernel32.DLL, que liberta todos os bytes para que já não possa usar a memória apontada por hglobal.

Além de FreeHGlobal, a Marshal classe fornece dois outros métodos de API de desalocação de memória: DestroyStructure e FreeCoTaskMem.

Aplica-se a

Ver também