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);
                }
            }

  • 相关阅读:
    Spring Boot 中使用 @Transactional 注解配置事务管理
    springboot 整合Swagger2的使用
    Vue的参数请求与传递
    SpringMVC的全局异常处理
    SpringBoot集成MyBatis的Bean配置方式
    Springboot整合通用mapper
    个人作业——软件工程实践总结作业
    团队作业第二次—项目选题报告(追光的人)
    结对第二次—文献摘要热词统计及进阶需求
    结对第一次—原型设计(文献摘要热词统计)
  • 原文地址:https://www.cnblogs.com/panjun/p/2812552.html
Copyright © 2011-2022 走看看