• c# 调用c++sdk时结构体与byte数组互转


     /// <summary>
            /// 由结构体转换为byte数组
            /// </summary>
            public static byte[] StructureToByte<T>(T structure)
            {
                int size = Marshal.SizeOf(typeof(T));
                byte[] buffer = new byte[size];
                IntPtr bufferIntPtr = Marshal.AllocHGlobal(size);
                try
                {
                    Marshal.StructureToPtr(structure, bufferIntPtr, true);
                    Marshal.Copy(bufferIntPtr, buffer, 0, size);
                }
                finally
                {
                    Marshal.FreeHGlobal(bufferIntPtr);
                }
                return buffer;
            }
    
            /// <summary>
            /// 由byte数组转换为结构体
            /// </summary>
            public static T ByteToStructure<T>(byte[] dataBuffer)
            {
                object structure = null;
                int size = Marshal.SizeOf(typeof(T));
                IntPtr allocIntPtr = Marshal.AllocHGlobal(size);
                try
                {
                    Marshal.Copy(dataBuffer, 0, allocIntPtr, size);
                    structure = Marshal.PtrToStructure(allocIntPtr, typeof(T));
                }
                finally
                {
                    Marshal.FreeHGlobal(allocIntPtr);
                }
                return (T)structure;
            }

     转载

  • 相关阅读:
    Poj2033
    CodeForces 540
    CodeForces 548
    LeetCode#2 Add Two Numbers
    CodeForces 544A
    POJ 2431Expedition
    HLG1116-选美大赛
    清华学堂 列车调度(Train)
    清华学堂 LightHouse
    清华学堂 Range
  • 原文地址:https://www.cnblogs.com/macT/p/12122786.html
Copyright © 2020-2023  润新知