HOW TO:使用指標複製位元組陣列 (C# 程式設計手冊)
更新:2007 年 11 月
下列範例使用指標在陣列之間複製位元組。
這個範例使用 unsafe 關鍵字,這能允許在 Copy 方法內使用指標。fixed 陳述式是用於宣告指向來源和目標陣列的指標。這會「固定」(Pin) 來源和目的地陣列在記憶體中的位置,如此一來就不會因記憶體回收而移動。這些記憶體區塊會在 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
*/