How do I copy bytes into a struct variable in C#?

我的未来我决定 提交于 2019-12-12 02:25:35

问题


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
}

回答1:


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)



来源:https://stackoverflow.com/questions/31045358/how-do-i-copy-bytes-into-a-struct-variable-in-c

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