|
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950 |
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Runtime.InteropServices;
- using System.Text;
- using System.Threading.Tasks;
-
- namespace BPASmartClient.GSIceCream
- {
- public class IcPack
- {
- private const int BASIC_LENGTH = 5;
- 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;
- }
- }
- }
|