1、struct转换为byte[]
static   byte[]   StructToBytes(object   structObj)  
  {  
  int   size   =     Marshal.SizeOf(structObj);  
  IntPtr   buffer   =   Marshal.AllocHGlobal(size);  
  try  
  {  
  Marshal.StructureToPtr(structObj,   buffer,   false);  
  byte[]   bytes   =   new   byte[size];  
  Marshal.Copy(buffer,   bytes,   0,   size);  
  return   bytes;  
  }  
  finally  
  {  
  Marshal.FreeHGlobal(buffer);  
  }  
   
  }   
   2、byte[]转换为struct
  static   object   BytesToStruct(byte[]   bytes,   Type   strcutType)  
  {  
  int   size   =     Marshal.SizeOf(strcutType);  
  IntPtr   buffer   =   Marshal.AllocHGlobal(size);  
  try  
  {  
  Marshal.Copy(bytes,   0,   buffer,   size);  
  return   Marshal.PtrToStructure(buffer,   strcutType);  
  }  
  finally  
  {  
  Marshal.FreeHGlobal(buffer);  
  }  
  }

相关文章:

猜你喜欢
  • 2021-05-21
  • 2022-12-23
  • 2021-08-04
  • 2021-12-25
  • 2021-10-28
相关资源
相似解决方案