Fast memcpy in C#

一曲冷凌霜 提交于 2019-12-06 15:58:12

问题


I want to write a C# method with prototype like this:

void memcpy(byte[] dst, int dstOffset, byte[] src, int srcOffset, int len);

I have 2 options for this method:

1.

void memcpy(byte[] dst, int dstOffset, byte[] src, int srcOffset, int len)
{
    for (int i = 0; i < len; i++)
    {
        dst[dstOffset + i] = src[srcOffset + i];
    }
}

2.

void memcpy(byte[] dst, int dstOffset, byte[] src, int srcOffset, int len)
{
    IntPtr intPtr = getIntPtr(dst, dstOffset);
    System.Runtime.InteropServices.Marshal.Copy(src, srcOffset, intPtr, len);
}

IntPtr getIntPtr(byte[] buffer, int offset)
{
    IntPtr intPtr;
    unsafe
    {
        fixed (byte* p1 = buffer)
        {
            byte* p2 = p1 + offset;
            intPtr = (IntPtr)p2;
        }
    }
    return intPtr;
}

Questions:

A. I guess option 2 is faster than option 1, is it right?

B. Is there another faster method?

Thanks a lot.


回答1:


Option #2 is broken, since you're using the pointer after the object it points to is no longer fixed. Pointers obtained within a fixed block may only be used inside that same fixed block. And it seems like you should have used Marshal.UnsafeAddrOfPinnedArrayElement anyway (and use it only inside a fixed block pinning the array).

Have a look at Buffer.BlockCopy.



来源:https://stackoverflow.com/questions/15963001/fast-memcpy-in-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!