IntPtr.ToPointer Método

Definição

Importante

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

Converte o valor desta instância num ponteiro para um tipo não especificado.

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

Devoluções

Void*

Um ponteiro para Void; ou seja, um ponteiro para memória contendo dados de um tipo não especificado.

Atributos

Exemplos

O exemplo seguinte utiliza ponteiros geridos para inverter os caracteres num array. Depois de inicializar um String objeto e obter o seu comprimento, faz o seguinte:

  • Chama o Marshal.StringToHGlobalAnsi método para copiar a string Unicode para memória não gerida como caracteres ANSI (de um byte). O método devolve um IntPtr objeto que aponta para o início da cadeia não gerida.

  • Chama o Marshal.AllocHGlobal método para alocar o mesmo número de bytes que ocupa a cadeia não gerida. O método devolve um IntPtr objeto que aponta para o início do bloco de memória não gerido.

  • Chama o ToPointer método para obter um ponteiro não gerido para o endereço inicial da cadeia e para o bloco de memória não gerido, e adiciona um a menos do que o comprimento da cadeia ao endereço inicial da cadeia ANSI. Como o apontador de string não gerido agora aponta para o fim da string, a operação de cópia irá copiar um carácter do final da string para o início do bloco de memória.

  • Utiliza um loop para copiar cada carácter da string para o bloco de memória não gerido. Após cada operação de cópia, decremente o ponteiro para o endereço da próxima localização na string ANSI não gerida e incrementa o ponteiro para o próximo endereço no bloco não gerido.

  • Chama para Marshal.PtrToStringAnsi converter o bloco de memória não gerida contendo a string ANSI copiada para um objeto Unicode String gerido.

  • Após exibir as cadeias originais e invertidas, chama o Marshal.FreeHGlobal método para libertar a memória alocada para a cadeia ANSI não gerida e o bloco de memória não gerido.

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
#nowarn "9"
open System.Runtime.InteropServices
open FSharp.NativeInterop

[<EntryPoint>]
let main _ =
    let stringA = "I seem to be turned around!"
    let mutable copylen = stringA.Length

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

    let mutable src: byte nativeptr = sptr.ToPointer() |> NativePtr.ofVoidPtr
    let mutable dst: byte nativeptr = dptr.ToPointer() |> NativePtr.ofVoidPtr

    if copylen > 0 then
        // set the source pointer to the end of the string
        // to do a reverse copy.
        src <- 
            NativePtr.toNativeInt src + nativeint (copylen - 1) 
            |> NativePtr.ofNativeInt

        while copylen > 0 do
            copylen <- copylen - 1
            NativePtr.read src |> NativePtr.write dst
            dst <- NativePtr.toNativeInt dst + 1n |> NativePtr.ofNativeInt
            src <- NativePtr.toNativeInt src - 1n |> NativePtr.ofNativeInt
        NativePtr.write dst 0uy

    let stringB = Marshal.PtrToStringAnsi dptr

    printfn $"Original:\n{stringA}\n"
    printfn $"Reversed:\n{stringB}"

    // Free HGlobal memory
    Marshal.FreeHGlobal dptr
    Marshal.FreeHGlobal sptr
    0

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

Aplica-se a