12345678910111213141516171819202122232425262728293031323334353637383940414243444546 |
- using System;
- using System.Collections.Generic;
- using System.IO;
- using System.Runtime.InteropServices;
- using System.Runtime.Serialization.Formatters.Binary;
- using System.Text;
- namespace Ips.Library.Basic
- {
- public static class BinaryUitl
- {
- public static byte[] StructToBytes<T>(T obj) where T : struct
- {
- int size = Marshal.SizeOf(obj);
- IntPtr ptr = Marshal.AllocHGlobal(size);
- byte[] buf = new byte[size];
- try
- {
- Marshal.StructureToPtr(obj, ptr, false);
- Marshal.Copy(ptr, buf, 0, buf.Length);
- }
- finally
- {
- Marshal.FreeHGlobal(ptr);
- }
- return buf;
- }
- public static T BytesToStruct<T>(byte[] buf, int startIndex = 0) where T : struct
- {
- int size = Marshal.SizeOf<T>();
- IntPtr ptr = Marshal.AllocHGlobal(size);
- T result;
- try
- {
- Marshal.Copy(buf, startIndex, ptr, size);
- result = Marshal.PtrToStructure<T>(ptr);
- }
- finally
- {
- Marshal.FreeHGlobal(ptr);
- }
- return result;
- }
- }
- }
|