Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best alternative to Buffer.MemoryCopy pre .NET 4.6

Tags:

c#

.net

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?

like image 599
Loocid Avatar asked Jan 31 '19 04:01

Loocid


1 Answers

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.

like image 112
TheGeneral Avatar answered Sep 28 '22 06:09

TheGeneral