Marshal.StringToHGlobalAnsi(String) Método
Definição
Importante
Algumas informações dizem respeito a um produto pré-lançado que pode ser substancialmente modificado antes de ser lançado. A Microsoft não faz garantias, de forma expressa ou implícita, em relação à informação aqui apresentada.
Copia o conteúdo de um gestor String para memória não gerida, convertendo para formato ANSI à medida que copia.
public:
static IntPtr StringToHGlobalAnsi(System::String ^ s);
[System.Security.SecurityCritical]
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
Parâmetros
- s
- String
Uma sequência gerida para ser copiada.
Devoluções
nativeint
O endereço, na memória não gerida, para onde s foi copiado, ou 0 se s for null.
- Atributos
Exceções
Há memória insuficiente disponível.
O s parâmetro excede o comprimento máximo permitido pelo sistema operativo.
Exemplos
O exemplo seguinte demonstra como converter o conteúdo de uma classe gerida String para memória não gerida e depois descartar a memória não gerida quando terminar.
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);
}
}
Observações
StringToHGlobalAnsi é útil para marshaling personalizado ou ao misturar código gerido e não gerido. Como este método aloca a memória não gerida necessária para uma cadeia, liberte sempre a memória chamando FreeHGlobal. StringToHGlobalAnsi fornece a funcionalidade oposta de Marshal.PtrToStringAnsi.
Este método copia caracteres nulos embutidos e inclui um carácter nulo terminante.