Is there a way to transfer a memory block to C #?

If you want to make a copy of memory between two arrays, there is an Array.Copy function in .NET:

 char[] GetCopy(char[] buf) { char[] result = new char[buf.Length]; Array.Copy(buf, result); return result; } 

It is usually faster than manually for-looping to copy all the characters in buf to result , because it is a block copy operation that simply takes a piece of memory and writes it to the destination.

Similarly, if I were instead given char* and int with its size, what are my options? Here are the ones I reviewed:

  • Buffer.BlockCopy : src and dst required to be arrays
  • Buffer.MemoryCopy : exactly what I'm looking for, but only available on .NET Desktop
  • Marshal.Copy : in .NET 2.0 supported

Or, if there is no alternative, is there some way to build an array from a char* pointer and an int length? If I could do this, I could just convert the pointers to arrays and pass them to Array.Copy.

I am not looking for for-loops because, because I said that they are not very efficient compared to block copies, but if this is the only way, I think it should be done.

TL DR: I am mostly looking for memcpy() , but in C # and can be used in PCL.

+5
source share
2 answers

You declare that Marshal.Copy will no longer be supported, however, in the Marshal documentation for the class, I cannot find any signs for this.

Quite the contrary, the class is available for the following framework versions: 4.6, 4.5, 4, 3.5, 3.0, 2.0, 1.1

One possible implementation of a utility function based on this method would be:

 public static void CopyFromPtrToPtr(IntPtr src, uint srcLen, IntPtr dst, uint dstLen) { var buffer = new byte[srcLen]; Marshal.Copy(src, buffer, 0, buffer.Length); Marshal.Copy(buffer, 0, dst, (int)Math.Min(buffer.Length, dstLen)); } 

However, it is possible that copying bytes from IntPtr to byte[] and vice versa negates any possible performance gain when fixing insecure memory and copying it in a loop.

Depending on how portable the code should be, you can also use P / Invoke to actually use the memcpy method. This should work well on Windows 2000 and later (all systems on which the Microsoft Visual C runtime library is installed).

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

Edit: The second approach is not suitable for portable class libraries, however the first will be.

+2
source

I don’t remember which built-in APIs have BCL, but you can copy the memcpy BCL code and use it. Use a Reflector and search for "memcpy" to find it. Insecure code is well defined and portable.

+1
source

All Articles