zoukankan      html  css  js  c++  java
  • 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);
                }
            }

  • 相关阅读:
    预备作业02:体会做中学(Learning By Doing)
    寒假作业01
    20210418第 237 场周赛(一)
    机器学习第七堂课20210415
    云计算与信息安全第七节课20210413
    操作系统第七堂课2021年0412内存管理基础
    机器学习第六堂课20210408
    云计算与信息安全第六节课20210406
    机器学习第五节课20210401
    云计算与信息安全第五堂课20210330
  • 原文地址:https://www.cnblogs.com/panjun/p/2812552.html
Copyright © 2011-2022 走看看