Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the C# equivalent of memcpy array to int?

Tags:

EDIT: I'm considering this question different from the potential duplicate because none of the answers on that one contain the approach I went with which is the BitConverter class. In case me marking this as not a duplicate gets rid of the potential duplicate question link here it is.

I'm wondering what the c# equivalent of this code is considering each element in the array is a byte and it's getting copied to an int.

byte offsetdata[sizeof(int)] = { 0,0,0,0 };
offsetdata[0] = m_Response[responseIndex++];
offsetdata[1] = m_Response[responseIndex++];
offsetdata[2] = m_Response[responseIndex++];
offsetdata[3] = m_Response[responseIndex++];
int offset = 0;
memcpy(&offset, offsetdata, sizeof offset);
m_ZOffset = offset;
like image 613
m4gik Avatar asked Mar 28 '19 00:03

m4gik


2 Answers

It really seems you just want to use

  • BitConverter.ToInt32 Method

Returns a 32-bit signed integer converted from four bytes at a specified position in a byte array

int offset =  BitConverter.ToInt32(somebyteData,0);

Note : Beware of the endianness

Or you could just use the the shift operators

  • << operator (C# Reference)

  • <<= operator (C# Reference)

  • >> operator (C# Reference)

  • >>= operator (C# Reference)

Though if you want to use memcpy, It depends what overloads you need, you can just P/invoke it if you want

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

However, for pointers the last 2 are probably good equivalents, with Marshal.Copy having by far the most versatility

  • Buffer.BlockCopy

Copies a specified number of bytes from a source array starting at a particular offset to a destination array starting at a particular offset.

  • Array.Copy

Copies a range of elements in one Array to another Array and performs type casting and boxing as required.

  • Unsafe.CopyBlock Method

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

  • Marshal.Copy

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

like image 158
TheGeneral Avatar answered Sep 29 '22 09:09

TheGeneral


This is possibly a duplicate, but I don't know how to mark it. Here is the original post: memcpy function in c#

From the other post there appear to be several options:

  1. Array.Copy
  2. Object.MemberwiseClone
  3. ICloneable Interface
like image 20
Matthew Salvatore Viglione Avatar answered Sep 29 '22 08:09

Matthew Salvatore Viglione