IntPtr.ToPointer Método

Definição

Importante

Esta API não está em conformidade com CLS.

Converte o valor dessa instância em um ponteiro para um tipo não especificado.Converts the value of this instance to a pointer to an unspecified type.

public:
 void* ToPointer();
[System.CLSCompliant(false)]
public void* ToPointer ();
[<System.CLSCompliant(false)>]
member this.ToPointer : unit -> nativeptr<unit>

Retornos

Void*

Um ponteiro para Void, ou seja, um ponteiro para a memória que contém dados de um tipo não especificado.A pointer to Void; that is, a pointer to memory containing data of an unspecified type.

Atributos

Exemplos

O exemplo a seguir usa ponteiros gerenciados para reverter os caracteres em uma matriz.The following example uses managed pointers to reverse the characters in an array. Depois de inicializar um String objeto e obter seu comprimento, ele faz o seguinte:After it initializes a String object and gets its length, it does the following:

  • Chama o Marshal.StringToHGlobalAnsi método para copiar a cadeia de caracteres Unicode para memória não gerenciada como caracteres ANSI (um byte).Calls the Marshal.StringToHGlobalAnsi method to copy the Unicode string to unmanaged memory as ANSI (one-byte) characters. O método retorna um IntPtr objeto que aponta para o início da cadeia de caracteres não gerenciada.The method returns an IntPtr object that points to the beginning of the unmanaged string.

  • Chama o Marshal.AllocHGlobal método para alocar o mesmo número de bytes que a cadeia de caracteres não gerenciada ocupa.Calls the Marshal.AllocHGlobal method to allocate the same number of bytes as the unmanaged string occupies. O método retorna um IntPtr objeto que aponta para o início do bloco de memória não gerenciado.The method returns an IntPtr object that points to the beginning of the unmanaged block of memory.

  • Chama o ToPointer método para obter um ponteiro não gerenciado para o endereço inicial da cadeia de caracteres e o bloco de memória não gerenciado e adiciona um menor que o comprimento da cadeia de caracteres ao endereço inicial da cadeia de caracteres ANSI.Calls the ToPointer method to get an unmanaged pointer to the starting address of the string and the unmanaged block of memory, and adds one less than the length of the string to the starting address of the ANSI string. Como o ponteiro de cadeia de caracteres não gerenciada agora aponta para o final da cadeia de caracteres, a operação de cópia copiará um caractere do final da cadeia de caracteres para o início do bloco de memória.Because the unmanaged string pointer now points to the end of the string, the copy operation will copy a character from the end of the string to the start of the memory block.

  • Usa um loop para copiar cada caractere da cadeia de caracteres para o bloco de memória não gerenciado.Uses a loop to copy each character from the string to the unmanaged block of memory. Após cada operação de cópia, ela diminui o ponteiro para o endereço do próximo local na cadeia de caracteres ANSI não gerenciada e incrementa o ponteiro para o próximo endereço no bloco não gerenciado.After each copy operation, it decrements the pointer to the address of the next location in the unmanaged ANSI string and increments the pointer to the next address in the unmanaged block.

  • Chama o Marshal.PtrToStringAnsi para converter o bloco de memória não gerenciada que contém a cadeia de caracteres ANSI copiada em um objeto Unicode gerenciado String .Calls the Marshal.PtrToStringAnsi to convert the unmanaged memory block containing the copied ANSI string to a managed Unicode String object.

  • Depois de exibir as cadeias de caracteres originais e inversas, o chama o Marshal.FreeHGlobal método para liberar a memória alocada para a cadeia de caracteres ANSI não gerenciada e o bloco de memória não gerenciado.After displaying the original and reversed strings, calls the Marshal.FreeHGlobal method to free the memory allocated for the unmanaged ANSI string and the unmanaged block of memory.

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

class NotTooSafeStringReverse
{
public:
    static void Main()
    {
        String^ stringA = "I seem to be turned around!";
        int copylen = stringA->Length;

        // Allocate HGlobal memory for source and destination strings
        IntPtr sptr = Marshal::StringToHGlobalAnsi(stringA);
        IntPtr dptr = Marshal::AllocHGlobal(copylen + 1);

        char *src = (char *)sptr.ToPointer();
        char *dst = (char *)dptr.ToPointer();

        if (copylen > 0)
        {
            // set the source pointer to the end of the string
            // to do a reverse copy.
            src += copylen - 1;

            while (copylen-- > 0)
            {
                *dst++ = *src--;
            }
            *dst = 0;
        }
        String^ stringB = Marshal::PtrToStringAnsi(dptr);

        Console::WriteLine("Original:\n{0}\n", stringA);
        Console::WriteLine("Reversed:\n{0}", stringB);

        // Free HGlobal memory
        Marshal::FreeHGlobal(dptr);
        Marshal::FreeHGlobal(sptr);
    }
};

int main()
{
    NotTooSafeStringReverse::Main();
}

// The progam has the following output:
//
// Original:
// I seem to be turned around!
//
// Reversed:
// !dnuora denrut eb ot mees I
using System;
using System.Runtime.InteropServices;

class NotTooSafeStringReverse
{
    static public void Main()
    {
        string stringA = "I seem to be turned around!";
        int copylen = stringA.Length;

        // Allocate HGlobal memory for source and destination strings
        IntPtr sptr = Marshal.StringToHGlobalAnsi(stringA);
        IntPtr dptr = Marshal.AllocHGlobal(copylen + 1);

        // The unsafe section where byte pointers are used.
        unsafe
        {
            byte *src = (byte *)sptr.ToPointer();
            byte *dst = (byte *)dptr.ToPointer();

            if (copylen > 0)
            {
                // set the source pointer to the end of the string
                // to do a reverse copy.
                src += copylen - 1;

                while (copylen-- > 0)
                {
                    *dst++ = *src--;
                }
                *dst = 0;
            }
        }
        string stringB = Marshal.PtrToStringAnsi(dptr);

        Console.WriteLine("Original:\n{0}\n", stringA);
        Console.WriteLine("Reversed:\n{0}", stringB);

        // Free HGlobal memory
        Marshal.FreeHGlobal(dptr);
        Marshal.FreeHGlobal(sptr);
    }
}

// The progam has the following output:
//
// Original:
// I seem to be turned around!
//
// Reversed:
// !dnuora denrut eb ot mees I

Aplica-se a