C#下,struct与字节数组的相互转换

来源:互联网 发布:上海跳跃网络吧爆吧 编辑:程序博客网 时间:2024/05/21 09:38
public struct TControlRequest
{
      public int     Code;               // command code
      public int     UserID;             // user id, 0=inner system
      public int     DevID;              // device id
      public unsafe fixed char    Param[200];         // parament
};
 
   public struct TControlResponse
   {
      public int     Result;             // result
      public unsafe fixed char Param[200];         // parament of result
   };
 
      //将TControlRequest转换为字节数组
      private byte[] TControlRequestToBytes(TControlRequest request)
      {
         int iSize = Marshal.SizeOf(typeof(TControlRequest));
         IntPtr pCertCont = Marshal.AllocHGlobal(iSize);
         Marshal.StructureToPtr(request, pCertCont, true);
         byte[] myWriteBuffer = new byte[iSize];
         Marshal.Copy(pCertCont, myWriteBuffer, 0, iSize);
         return myWriteBuffer;
      }
 
      //将字节数组转换为TControlResponse
      private TControlResponse BytesToTcontrolResponse(byte[] myReadBuffer)
      {
         TControlResponse response = new TControlResponse();
         try
         {
            int iSize = Marshal.SizeOf(typeof(TControlResponse));
            IntPtr pCertCont = Marshal.AllocHGlobal(iSize);
            Marshal.Copy(myReadBuffer, 0, pCertCont, iSize);
            response = (TControlResponse)Marshal.PtrToStructure(pCertCont, typeof(TControlResponse));
         }
         catch(ArgumentException)
         {
         }
         return response;
      }
原创粉丝点击