다음을 통해 공유


방법: 포인터를 사용하여 바이트 배열 복사(C# 프로그래밍 가이드)

업데이트: 2010년 6월

다음 예제에서는 포인터를 사용하여 배열 간에 바이트를 복사합니다.

이 예제에서는 Copy 메서드 내에서 포인터를 사용할 수 있게 해주는 unsafe 키워드를 사용합니다. fixed 문은 소스 및 대상 배열에 대한 포인터를 선언하는 데 사용됩니다. 이렇게 하면 소스 및 대상 배열의 메모리 내 위치가 고정되어 가비지 수집에 의해 이동하지 않습니다. 배열의 메모리 블록은 fixed 블록이 완료될 때 고정이 해제됩니다. 이 예제의 Copy 메서드는 unsafe 키워드를 사용하기 때문에 /unsafe 컴파일러 옵션을 사용하여 컴파일되어야 합니다. Visual Studio에서 이 옵션을 설정하려면 프로젝트 이름을 마우스 오른쪽 단추로 클릭한 다음 속성을 클릭합니다. 빌드 탭에서 안전하지 않은 코드 허용을 선택합니다.

예제

// compile with: /unsafe
class TestCopy
{
    // The unsafe keyword allows pointers to be used in the following method.

    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)
        {
            // Set the starting points in source and target for the copying.
            byte* ps = pSource + sourceOffset;
            byte* pt = pTarget + targetOffset;

            // Copy the specified number of bytes from source to target.
            for (int i = 0; i < count; i++)
            {
                *pt = *ps;
                pt++;
                ps++;
            }
        }
    }

    static void Main()
    {
        // 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
*/

참고 항목

참조

안전하지 않은 코드 및 포인터(C# 프로그래밍 가이드)

/unsafe(C# 컴파일러 옵션)

개념

C# 프로그래밍 가이드

가비지 수집

변경 기록

날짜

변경 내용

이유

2010년 6월

예제가 업데이트되고 명확한 설명이 추가되었습니다.

고객 의견