Marshal.StringToHGlobalAnsi(String) 方法

定义

将托管 String 的内容复制到非托管内存,并在复制时转换为 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

要复制的托管字符串。

返回

IntPtr

nativeint

非托管内存中将 s 复制到其中的地址;如果 snull,则为 0。

属性

例外

没有足够的可用内存。

s 参数超过了操作系统所允许的最大长度。

示例

以下示例演示如何将托管 String 类的内容转换为非托管内存,然后在完成后释放非托管内存。

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

注解

StringToHGlobalAnsi 对于自定义封送处理或混合托管和非托管代码时非常有用。 由于此方法分配字符串所需的非托管内存,因此请始终通过调用 FreeHGlobal释放内存。 StringToHGlobalAnsi 提供 相反的功能 Marshal.PtrToStringAnsi

此方法复制嵌入的空字符,并包含终止 null 字符。

适用于

另请参阅