Compartilhar via


Como: Usar ponteiros para copiar uma matriz de bytes (guia de programação translation from VPE for Csharp)

O exemplo a seguir utiliza ponteiros para copiar bytes de um array para outro usando ponteiros.

Este exemplo usa o não seguro palavra-de chave, que permite que os ponteiros para ser usado dentro de Copy método. The fixo demonstrativo é usada para declarar os ponteiros para os arrays de fonte e destino.Este pinos o local de fonte e destino arrays na memória para que eles não serão movidos pelo coletor de lixo.Esses blocos de memória serão desagregados quando o fixed bloco completa. Como a função copiar esse exemplo usa o unsafe palavra-chave, ela deve ser compilada com /unsafe opção do compilador.

Exemplo

// compile with: /unsafe
class TestCopy
{
    // The unsafe keyword allows pointers to be used within the following method:
    static unsafe void Copy(byte[] src, int srcIndex, byte[] dst, int dstIndex, int count)
    {
        if (src == null || srcIndex < 0 ||
            dst == null || dstIndex < 0 || count < 0)
        {
            throw new System.ArgumentException();
        }

        int srcLen = src.Length;
        int dstLen = dst.Length;
        if (srcLen - srcIndex < count || dstLen - dstIndex < count)
        {
            throw new System.ArgumentException();
        }

        // The following fixed statement pins the location of the src and dst objects
        // in memory so that they will not be moved by garbage collection.
        fixed (byte* pSrc = src, pDst = dst)
        {
            byte* ps = pSrc;
            byte* pd = pDst;

            // Loop over the count in blocks of 4 bytes, copying an integer (4 bytes) at a time:
            for (int i = 0 ; i < count / 4 ; i++)
            {
                *((int*)pd) = *((int*)ps);
                pd += 4;
                ps += 4;
            }

            // Complete the copy by moving any bytes that weren't moved in blocks of 4:
            for (int i = 0; i < count % 4 ; i++)
            {
                *pd = *ps;
                pd++;
                ps++;
            }
        }
    }

    static void Main()
    {
        byte[] a = new byte[100];
        byte[] b = new byte[100];

        for (int i = 0; i < 100; ++i)
        {
            a[i] = (byte)i;
        }

        Copy(a, 0, b, 0, 100);
        System.Console.WriteLine("The first 10 elements are:");

        for (int i = 0; i < 10; ++i) 
        {
            System.Console.Write(b[i] + " ");
        }
        System.Console.WriteLine("\n");
    }
}
/* Output:
    The first 10 elements are:
    0 1 2 3 4 5 6 7 8 9        
*/

Consulte também

Tarefas

Exemplo de código não seguro

Conceitos

Guia de Programação C#

Referência

Não seguro código e ponteiros (guia de programação C#)

/unsafe (permitir sem segurança modo) (opções do compilador de C#)

Outros recursos

Coleta de Lixo