Best alternative to Buffer.MemoryCopy pre .NET 4.6

ぐ巨炮叔叔 提交于 2021-02-19 02:03:48

问题


I'm trying to downgrade some .NET 4.6 code to .NET 4.5.

This is the code block im working with at the moment:

fixed (byte* destination = dataBytes)
{
    Buffer.MemoryCopy(data, destination, dataLength, dataLength);
}

data is byte* type so I don't know if Buffer.BlockCopy() is a reasonable replacement since it takes in Arrays.

Any ideas?


回答1:


You are right that Buffer.MemoryCopy is .Net 4.6 or higher, Buffer.BlockCopy doesn't have the the desired overloads, and Array.Copy is out of the question also.

You could use the following however it will be slow

fixed (byte* pSource = source, pTarget = target)
    for (int i = 0; i < count; i++)
        pTarget[targetOffset + i] = pSource[sourceOffset + i];

If all else fails you can pinvoke memcpy from msvcrt.dll

[DllImport("msvcrt.dll", EntryPoint = "memcpy", CallingConvention = CallingConvention.Cdecl, SetLastError = false)]
public static extern IntPtr memcpy(IntPtr dest, IntPtr src, UIntPtr count);

Also for .Net 4.5 you can use System.Runtime.CompilerServices.Unsafe

Unsafe.CopyBlock Method

CopyBlock(Void*, Void*, UInt32)

Copies a number of bytes specified as a long integer value from one address in memory to another.


Lastly, you can use Marshal.Copy if you don't mind ending up in an array. However it doesn't have a pointer to pointer overload.

Copies data from a managed array to an unmanaged memory pointer, or from an unmanaged memory pointer to a managed array.



来源:https://stackoverflow.com/questions/54453119/best-alternative-to-buffer-memorycopy-pre-net-4-6

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