使用非托管代码进行字节数组的快速拷贝
今天在阅读MSDN时发现了该方法示例,感觉在C#环境下也可以这样,真是一个不错的idea,不过没有具体验证过其效率,有兴趣的朋友可以自己验证一下。
1
class TestCopy2


{3
// The unsafe keyword allows pointers to be used within the following method:4
static unsafe void Copy(byte[] src, int srcIndex, byte[] dst, int dstIndex, int count)5

{6
if (src == null || srcIndex < 0 ||7
dst == null || dstIndex < 0 || count < 0)8

{9
throw new System.ArgumentException();10
}11

12
int srcLen = src.Length;13
int dstLen = dst.Length;14
if (srcLen - srcIndex < count || dstLen - dstIndex < count)15

{16
throw new System.ArgumentException();17
}18

19
// The following fixed statement pins the location of the src and dst objects20
// in memory so that they will not be moved by garbage collection.21
fixed (byte* pSrc = src, pDst = dst)22

{23
byte* ps = pSrc;24
byte* pd = pDst;25

26
// Loop over the count in blocks of 4 bytes, copying an integer (4 bytes) at a time:27
for (int i = 0 ; i < count / 4 ; i++)28

{29
*((int*)pd) = *((int*)ps);30
pd += 4;31
ps += 4;32
}33

34
// Complete the copy by moving any bytes that weren't moved in blocks of 4:35
for (int i = 0; i < count % 4 ; i++)36

{37
*pd = *ps;38
pd++;39
ps++;40
}41
}42
}43

44
static void Main()45

{46
byte[] a = new byte[100];47
byte[] b = new byte[100];48

49
for (int i = 0; i < 100; ++i)50

{51
a[i] = (byte)i;52
}53

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

57
for (int i = 0; i < 10; ++i) 58

{59
System.Console.Write(b[i] + " ");60
}61
System.Console.WriteLine("\n");62
}63
}


浙公网安备 33010602011771号