public bool Write(RadioHeader header, object Message, int MessageSize) { try { byte[] buffer = new byte[Marshal.SizeOf(typeof(RadioHeader)) + MessageSize]; IntPtr headerPointer = Marshal.AllocHGlobal(Marshal.SizeOf(header)); Marshal.StructureToPtr(header, headerPointer, false); Marshal.Copy(headerPointer, buffer, 0, Marshal.SizeOf(header)); BinaryFormatter bf = new BinaryFormatter(); using (var ms = new MemoryStream()) { bf.Serialize(ms, Message); Array.Copy(ms.ToArray(), 0, buffer, Marshal.SizeOf(typeof(RadioHeader)), MessageSize); } this.serialComm.Write(buffer, Marshal.SizeOf(buffer)); } catch { return(false); } return(true); }
private void SerialReader(byte[] buffer, int numBytes) { //Read message header GCHandle handle = GCHandle.Alloc(buffer, GCHandleType.Pinned); RadioHeader header = (RadioHeader)Marshal.PtrToStructure(handle.AddrOfPinnedObject(), typeof(RadioHeader)); handle.Free(); byte[] messageBuffer = new byte[numBytes - Marshal.SizeOf(typeof(RadioHeader))]; Array.Copy(buffer, Marshal.SizeOf(typeof(RadioHeader)), messageBuffer, 0, numBytes - Marshal.SizeOf(typeof(RadioHeader))); //add to message queue this.Messages.Add(new RadioMessage { Header = header, Message = messageBuffer }); }