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

  • 相关阅读:
    day01
    You need tcl 8.5 or newer in order to run the Redis test
    docker配置网络
    centos设置时间同步
    cacti 添加tomcat监控
    cacti 安装perl 和XML::Simple
    cacti 添加redis监控(远程服务器)
    cacti安装spine 解决WARNING: Result from CMD not valid. Partial Result: U错误
    cacti 添加mysql 监控 (远程服务器)
    centos 安装redis
  • 原文地址:https://www.cnblogs.com/panjun/p/2812552.html
Copyright © 2011-2022 走看看