Marshal.FreeHGlobal(IntPtr) メソッド

定義

プロセスのアンマネージ メモリから以前に割り当てられたメモリを解放します。

C#
[System.Security.SecurityCritical]
public static void FreeHGlobal(IntPtr hglobal);
C#
public static void FreeHGlobal(IntPtr hglobal);

パラメーター

hglobal
IntPtr

AllocHGlobal(IntPtr)に対する元の一致する呼び出しによって返されるハンドル。

属性

次の例では、FreeHGlobal メソッドの呼び出しを示します。 このコード例は、Marshal クラスに提供されるより大きな例の一部です。

C#
// Demonstrate how to call GlobalAlloc and
// GlobalFree using the Marshal class.
IntPtr hglobal = Marshal.AllocHGlobal(100);
Marshal.FreeHGlobal(hglobal);

次の例では、マネージド String クラスの内容をアンマネージ メモリに変換し、完了したらアンマネージ メモリを破棄する方法を示します。

C#
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);
    }
}

注釈

重要

このネイティブ メモリ アロケーターは、Windows プラットフォーム上の特定の Win32 API によって呼び出されたときに排他的に使用する必要があるレガシ API です。 .NET 6 以降を対象とする場合は、すべてのプラットフォームで NativeMemory クラスを使用してネイティブ メモリを割り当てます。 .NET 6 以前を対象とする場合は、すべてのプラットフォームで AllocCoTaskMem を使用してネイティブ メモリを割り当てます。

FreeHGlobal を使用すると、AllocHGlobalReAllocHGlobal、または同等のアンマネージ API メソッドによって割り当てられたグローバル ヒープから任意のメモリを解放できます。 hglobal パラメーターが IntPtr.Zero 場合、メソッドは何も実行しません。

FreeHGlobal は、Kernel32.DLLから LocalFree 関数を公開します。これによってすべてのバイトが解放されるため、hglobalが指すメモリを使用できなくなります。

FreeHGlobalに加えて、Marshal クラスには、DestroyStructureFreeCoTaskMemの 2 つのメモリ解放 API メソッドが用意されています。

適用対象

製品 バージョン
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9, 10
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 2.0, 2.1
UWP 10.0

こちらもご覧ください