struct和byte[]相互转换(用Marshal类实现)

转自[DotNet笔记]

相当于序列化与反序列化,但是不用借助外部文件
1、struct转换为byte[]

 1static   byte[]   StructToBytes(object   structObj)   
 2  {   
 3  int   size   =     Marshal.SizeOf(structObj);   
 4  IntPtr   buffer   =   Marshal.AllocHGlobal(size);   
 5  try   
 6  {   
 7  Marshal.StructureToPtr(structObj,   buffer,   false);   
 8  byte[]   bytes   =   new   byte[size];   
 9  Marshal.Copy(buffer,   bytes,   0,   size);   
10  return   bytes;   
11  }
   
12  finally   
13  {   
14  Marshal.FreeHGlobal(buffer);   
15  }
   
16    
17  }
 


 2、byte[]转换为struct

 1static   object   BytesToStruct(byte[]   bytes,   Type   strcutType)   
 2  {   
 3  int   size   =     Marshal.SizeOf(strcutType);   
 4  IntPtr   buffer   =   Marshal.AllocHGlobal(size);   
 5  try   
 6  {   
 7  Marshal.Copy(bytes,   0,   buffer,   size);   
 8  return   Marshal.PtrToStructure(buffer,   strcutType);   
 9  }
   
10  finally   
11  {   
12  Marshal.FreeHGlobal(buffer);   
13  }
   
14  }
 
15

posted on 2007-04-23 16:16  BugHunter  阅读(1130)  评论(0编辑  收藏  举报

导航