C#通过指针实现快速拷贝的方法
本文实例讲述了C#通过指针实现快速拷贝的方法。分享给大家供大家参考。具体实现方法如下:
//fastcopy.cs
//编译时使用:/unsafe
usingSystem;
classTest
{
//unsafe关键字允许在下列
//方法中使用指针:
staticunsafevoidCopy(byte[]src,intsrcIndex,byte[]dst,intdstIndex,intcount)
{
if(src==null||srcIndex<0||
dst==null||dstIndex<0||count<0)
{
thrownewArgumentException();
}
intsrcLen=src.Length;
intdstLen=dst.Length;
if(srcLen-srcIndex<count||dstLen-dstIndex<count)
{
thrownewArgumentException();
}
//以下固定语句固定
//src对象和dst对象在内存中的位置,以使这两个对象
//不会被垃圾回收移动。
fixed(byte*pSrc=src,pDst=dst)
{
byte*ps=pSrc;
byte*pd=pDst;
//以4个字节的块为单位循环计数,一次复制
//一个整数(4个字节):
for(intn=0;n<count/4;n++)
{
*((int*)pd)=*((int*)ps);
pd+=4;
ps+=4;
}
//移动未以4个字节的块移动的所有字节,
//从而完成复制:
for(intn=0;n<count%4;n++)
{
*pd=*ps;
pd++;
ps++;
}
}
}
staticvoidMain(string[]args)
{
byte[]a=newbyte[100];
byte[]b=newbyte[100];
for(inti=0;i<100;++i)
a[i]=(byte)i;
Copy(a,0,b,0,100);
Console.WriteLine("Thefirst10elementsare:");
for(inti=0;i<10;++i)
Console.Write(b[i]+"");
Console.WriteLine("\n");
}
}
希望本文所述对大家的C#程序设计有所帮助。