0

I have a struct abc and I want to copy bytes into a struct variable. Similar to memcpy in C/C++. I receive the bytes over socket and they are the bytes of the same struct abc variable.

[StructLayout(LayoutKind.Sequential, Pack = 1)]    
public struct abc
{ 
         public int a;
         public int b;
         public float c;
         public char[] d; //30 size
}
Biswarup Dass
  • 193
  • 1
  • 5
  • 19
  • 7
    This is basically a brittle approach - you're relying on the endianness of both machines being the same, for example. You'd need the char array to be `fixed`, too, I suspect. I would *strongly* recommend against using mutable structs like this in general, and definitely against assuming that the in-memory representation on one machine will be appropriate on another. – Jon Skeet Jun 25 '15 at 08:46
  • look at `Marshal.PtrToStructure()` and `Marshal.StructureToPtr()` methods – Dmitry Bychenko Jun 25 '15 at 08:46
  • 1
    While copying bytes directly is faster, consider to use serialization/deserialization to have data consistency while transporting them. – Sinatr Jun 25 '15 at 08:54
  • 1
    You will not be able to do this without resorting to `unsafe` code due to the need for a `fixed` array. You should solve this issue by using a `MemoryStream` stream reader attached to the input buffer to access the variables, and assign the read data to the struct members. Even then, you may have problems with endedness. See [Jon's answer here](http://stackoverflow.com/a/217993/106159) for a solution to that. – Matthew Watson Jun 25 '15 at 08:56

1 Answers1

0

You can convert the byte array to your structure as follows :

            int size = Marshal.SizeOf(typeof(abc));
            IntPtr ptr = Marshal.AllocHGlobal(size);

            Marshal.Copy(arr, 0, ptr, size);

            var struct = (abc)Marshal.PtrToStructure(ptr, typeof(abc));
            Marshal.FreeHGlobal(ptr);

struct is now your converted structure. Bear in mind the comments that have been made about this though (i.e. byte ordering)

auburg
  • 1,373
  • 2
  • 12
  • 22