Marshal.StringToHGlobalAnsi(String) メソッド

定義

マネージド String の内容をアンマネージド メモリにコピーし、コピー時に ANSI 形式に変換します。

C#
[System.Security.SecurityCritical]
public static IntPtr StringToHGlobalAnsi(string s);
C#
public static IntPtr StringToHGlobalAnsi(string? s);
C#
public static IntPtr StringToHGlobalAnsi(string s);

パラメーター

s
String

コピーされるマネージド文字列。

戻り値

IntPtr

s のコピー先となったアンマネージ メモリ内のアドレス。snull の場合は 0。

属性

例外

使用できるメモリが不足しています。

s パラメーターがオペレーティング システムで許可されている最大長を超えています。

次の例では、マネージド 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);
    }
}

注釈

StringToHGlobalAnsi は、カスタム マーシャリングや、マネージド コードとアンマネージド コードを混在する場合に便利です。 このメソッドは文字列に必要なアンマネージ メモリを割り当てるので、 を呼び出 FreeHGlobalして常にメモリを解放します。 StringToHGlobalAnsi は の逆の機能を Marshal.PtrToStringAnsi提供します。

このメソッドは、埋め込まれた null 文字をコピーし、終端の null 文字を含みます。

適用対象

製品 バージョン
.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

こちらもご覧ください