C++开发博客CSDN

C++中取出的字节数组转为结构

byte[] BytePara = 为从C++里取出的字节数组;

InfoDataStruct 为结构,循环将Byte数组里的内容转换为结构

 InfoDataStruct* p = (InfoDataStruct*)(BytePara+ (i * 55));

 InfoDataStruct dataStruct=  BytesToStruct<InfoDataStruct>(BytePara, (i * 55));

        ///不使用泛型,会使得编码繁琐。

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

        /// <summary>
        /// byte数组转为结构
        /// </summary>
        /// <typeparam name="T">结构</typeparam>
        /// <param name="bytes">数组</param>
        /// <param name="startIndex">起始位置</param>
        /// <returns></returns>
        public static T BytesToStruct<T>(byte[] bytes, int startIndex)
        {
            T Obj = default(T);
            Type strcutType = typeof(T);
            int size = Marshal.SizeOf(strcutType);
            IntPtr buffer = Marshal.AllocHGlobal(size);
            try
            {
                Marshal.Copy(bytes, startIndex, buffer, size);
                Obj= (T) Marshal.PtrToStructure(buffer, strcutType);
                return Obj;
            }
            finally
            {
                Marshal.FreeHGlobal(buffer);
            }
        }

posted @ 2012-12-11 11:09  纳凉亭子  阅读(1016)  评论(0编辑  收藏  举报