Marshal.StringToHGlobalAnsi(String) 方法

定義

將 Managed String 的內容複製到 Unmanaged 記憶體中,並在它複製時轉換成 ANSI 格式。

public:
 static IntPtr StringToHGlobalAnsi(System::String ^ s);
[System.Security.SecurityCritical]
public static IntPtr StringToHGlobalAnsi (string s);
public static IntPtr StringToHGlobalAnsi (string? s);
public static IntPtr StringToHGlobalAnsi (string s);
[<System.Security.SecurityCritical>]
static member StringToHGlobalAnsi : string -> nativeint
static member StringToHGlobalAnsi : string -> nativeint
Public Shared Function StringToHGlobalAnsi (s As String) As IntPtr

參數

s
String

要複製的 Managed 字串。

傳回

IntPtr

nativeint

Unmanaged 記憶體中複製 s 的目的位址,如果 snull 則為 0。

屬性

例外狀況

可用的記憶體不足。

s 參數超過作業系統所允許的最大長度。

範例

下列範例示範如何將 Managed String 類別的內容轉換為 Unmanaged 記憶體,然後在完成時處置 Unmanaged 記憶體。

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;

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

備註

StringToHGlobalAnsi 適用于自訂封送處理,或在混合 Managed 和 Unmanaged 程式碼時使用。 因為這個方法會配置字串所需的 Unmanaged 記憶體,所以一律呼叫 FreeHGlobal 來釋放記憶體。 StringToHGlobalAnsi 提供 的相反功能 Marshal.PtrToStringAnsi

這個方法會複製內嵌的 Null 字元,並包含終止的 Null 字元。

適用於

另請參閱