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

  • 相关阅读:
    Java-对象数组排序
    aoj 0118 Property Distribution
    poj 3009 Curling 2.0
    poj 1979 Red and Black
    AtCoder Regular Contest E
    AtCoder Beginner Contest 102
    AtCoder Beginner Contest 104
    SoundHound Inc. Programming Contest 2018
    poj 3233 Matrix Power Series
    poj 3734 Blocks
  • 原文地址:https://www.cnblogs.com/panjun/p/2812552.html
Copyright © 2011-2022 走看看