且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在C#中将字节复制到结构变量中?

更新时间:2023-02-03 15:53:06

您可以按如下所示将字节数组转换为您的结构:

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现在是您转换后的结构.请记住,尽管如此,注释(即字节顺序)

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