程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> .NET網頁編程 >> C# >> C#入門知識 >> 類結構體 與 byte[] 轉換類,byte轉換

類結構體 與 byte[] 轉換類,byte轉換

編輯:C#入門知識

類結構體 與 byte[] 轉換類,byte轉換


    public static class StructConvert
    {
        public static object BytesToStruct(byte[] bytes, Type strcutType)
        {
            int size = Marshal.SizeOf(strcutType);
            IntPtr buffer = Marshal.AllocHGlobal(size);
            try
            {
                Marshal.Copy(bytes, 0, buffer, size);
                return Marshal.PtrToStructure(buffer, strcutType);
            }
            finally
            {
                Marshal.FreeHGlobal(buffer);
            }
        }

        public static byte[] StructToBytes(object structObj)
        {
            int size = Marshal.SizeOf(structObj);
            IntPtr buffer = Marshal.AllocHGlobal(size);
            try
            {
                Marshal.StructureToPtr(structObj, buffer, false);
                byte[] bytes = new byte[size];
                Marshal.Copy(buffer, bytes, 0, size);
                return bytes;
            }
            finally
            {
                Marshal.FreeHGlobal(buffer);
            }
        }

    }

 類結構體示例,struct和class 均可轉換,根據項目需要

    [StructLayout(LayoutKind.Sequential, Pack = 1, CharSet = CharSet.Ansi)]
    public struct MapRecord
    {
        public int Id;
        public int Rebirth;
        public int CoorX;
        public int CoorY;
        public int CoorZ;

        [MarshalAs(UnmanagedType.ByValArray, SizeConst = 204)]
        public byte[] Unknown1;
        public int Dir;
        [MarshalAs(UnmanagedType.ByValArray, SizeConst = 32)]
        public byte[] Unknown2;
        public int MiniMap;
        [MarshalAs(UnmanagedType.ByValArray, SizeConst = 6)]
        public byte[] Unknown3;
    }

 

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved