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

1、struct转换为byte[]
+展开
-C#
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
+展开
-C#
 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);   
  }   
  } 



http://www.cnblogs.com/tuyile006/archive/2006/12/28/605962.html

加支付宝好友偷能量挖...


评论(0)网络
阅读(79)喜欢(0)Asp.Net/C#/WCF