Marshal.StringToHGlobalAuto(String) 方法

定義

複製 Managed String 的內容到 Unmanaged 記憶體中,如有需要則轉換成 ANSI 格式。

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

參數

s
String

要複製的 Managed 字串。

傳回

IntPtr

nativeint

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

屬性

例外狀況

可用的記憶體不足。

範例

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

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

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::StringToHGlobalAuto(managedString).ToPointer();

    // Pass the string to an unmanaged API.

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

    return 0;
}

備註

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

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

適用於

另請參閱