Gewusst wie: Verwenden von Zeigern zum Kopieren eines Bytearrays (C#-Programmierhandbuch)How to: Use Pointers to Copy an Array of Bytes (C# Programming Guide)

In folgendem Beispiel werden Zeiger verwendet, um Bytes aus einem Array in ein anderes zu kopieren.The following example uses pointers to copy bytes from one array to another.

In diesem Beispiel wird das Schlüsselwort unsafe verwendet, mit dem Sie Zeiger in der Copy-Methode verwenden können.This example uses the unsafe keyword, which enables you to use pointers in the Copy method. Die Anweisung fixed wird verwendet, um Zeiger auf das Quell- und Zielarray zu deklarieren.The fixed statement is used to declare pointers to the source and destination arrays. Diese fixed-Anweisung heftet den Speicherort des Quell- und Zielarrays im Speicher an, damit diese während der automatischen Speicherbereinigung nicht verschoben werden.The fixed statement pins the location of the source and destination arrays in memory so that they will not be moved by garbage collection. Die Speicherblöcke der Arrays werden gelöst, wenn der fixed-Block abgeschlossen wird.The memory blocks for the arrays are unpinned when the fixed block is completed. Da die Copy-Methode in diesem Beispiel das Schlüsselwort unsafe verwendet, muss sie mit der Compileroption -unsafe kompiliert werden.Because the Copy method in this example uses the unsafe keyword, it must be compiled with the -unsafe compiler option.

In diesem Beispiel werden Indizes anstelle eines zweiten nicht verwalteten Zeigers verwendet, um auf die Elemente beider Arrays zuzugreifen.This example accesses the elements of both arrays using indices rather than a second unmanaged pointer. Die Deklaration der Zeiger pSource und pTarget heftet die Arrays an.The declaration of the pSource and pTarget pointers pins the arrays. Dieses Feature ist ab C# 7.3 verfügbar.This feature is available starting with C# 7.3.

BeispielExample

static unsafe void Copy(byte[] source, int sourceOffset, byte[] target,
    int targetOffset, int count)
{
    // If either array is not instantiated, you cannot complete the copy.
    if ((source == null) || (target == null))
    {
        throw new System.ArgumentException();
    }

    // If either offset, or the number of bytes to copy, is negative, you
    // cannot complete the copy.
    if ((sourceOffset < 0) || (targetOffset < 0) || (count < 0))
    {
        throw new System.ArgumentException();
    }

    // If the number of bytes from the offset to the end of the array is 
    // less than the number of bytes you want to copy, you cannot complete
    // the copy. 
    if ((source.Length - sourceOffset < count) ||
        (target.Length - targetOffset < count))
    {
        throw new System.ArgumentException();
    }

    // The following fixed statement pins the location of the source and
    // target objects in memory so that they will not be moved by garbage
    // collection.
    fixed (byte* pSource = source, pTarget = target)
    {
        // Copy the specified number of bytes from source to target.
        for (int i = 0; i < count; i++)
        {
            pTarget[targetOffset + i] = pSource[sourceOffset + i];
        }
    }
}

static void UnsafeCopyArrays()
{
    // Create two arrays of the same length.
    int length = 100;
    byte[] byteArray1 = new byte[length];
    byte[] byteArray2 = new byte[length];

    // Fill byteArray1 with 0 - 99.
    for (int i = 0; i < length; ++i)
    {
        byteArray1[i] = (byte)i;
    }

    // Display the first 10 elements in byteArray1.
    System.Console.WriteLine("The first 10 elements of the original are:");
    for (int i = 0; i < 10; ++i)
    {
        System.Console.Write(byteArray1[i] + " ");
    }
    System.Console.WriteLine("\n");

    // Copy the contents of byteArray1 to byteArray2.
    Copy(byteArray1, 0, byteArray2, 0, length);

    // Display the first 10 elements in the copy, byteArray2.
    System.Console.WriteLine("The first 10 elements of the copy are:");
    for (int i = 0; i < 10; ++i)
    {
        System.Console.Write(byteArray2[i] + " ");
    }
    System.Console.WriteLine("\n");

    // Copy the contents of the last 10 elements of byteArray1 to the 
    // beginning of byteArray2.
    // The offset specifies where the copying begins in the source array.
    int offset = length - 10;
    Copy(byteArray1, offset, byteArray2, 0, length - offset);

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

        The first 10 elements of the copy are:
        0 1 2 3 4 5 6 7 8 9

        The first 10 elements of the copy are:
        90 91 92 93 94 95 96 97 98 99
    */
}

Siehe auchSee Also

C#-ProgrammierhandbuchC# Programming Guide
Unsicherer Code und ZeigerUnsafe Code and Pointers
-unsafe (C#-Compileroptionen)-unsafe (C# Compiler Options)
Garbage CollectionGarbage Collection