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

업데이트: 2007년 11월

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

이 예제에서는 Copy 메서드 내에서 포인터를 사용할 수 있도록 unsafe 키워드를 사용합니다. fixed 문은 소스 및 대상 배열에 대한 포인터를 선언하는 데 사용됩니다. 이렇게 하면 소스 및 대상 배열의 메모리 내 위치가 고정되어 가비지 수집에 의해 이동하지 않습니다. 이러한 메모리 블록은 fixed 블록의 실행이 완료되면 고정이 해제됩니다. 이 예제의 Copy 함수에서는 unsafe 키워드를 사용하므로 /unsafe 컴파일러 옵션을 사용하여 컴파일해야 합니다.

예제

// 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        
*/

참고 항목

작업

안전하지 않은 코드 샘플

개념

C# 프로그래밍 가이드

참조

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

/unsafe(Unsafe 모드 사용)(C# 컴파일러 옵션)

기타 리소스

가비지 수집