本文介绍了C#中的快速记忆的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想用这样的原型编写一个C#方法:

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

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

我对此方法有2个选择:

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;
}

问题:

A.我猜选项2比选项1快,对吗?

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

B.还有另一种更快的方法吗?

B. Is there another faster method?

非常感谢.

推荐答案

选项#2已损坏,因为您正在使用指向该对象的指针,该指针已不再固定.在fixed块内获得的指针只能在同一fixed块内使用.看来您应该使用 Marshal.UnsafeAddrOfPinnedArrayElement (并且只能在固定数组的fixed块内使用它).

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).

看看 Buffer.BlockCopy .

这篇关于C#中的快速记忆的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-13 13:22