Manipulate
Having allocated a memory chunk you can now write data anywhere inside the buffer. The most common methods are ReadBuffer and WriteBuffer. Much like TQTXStream, TManagedMemory also inherits from TDataTypeConverter, so you can use all the same conversion functions directly on the buffer object (!).
// Example: Building a simple data packet
var
Packet: TManagedMemory;
PacketID: uint16;
Message: string;
begin
PacketID := $F001;
Message := 'PING';
Packet := TManagedMemory.Create;
Packet.Allocate(100); // Allocate a 100-byte buffer
try
// Write the Packet ID (2 bytes) at offset 0
Packet.WriteBuffer(0, Packet.UInt16ToBytes(PacketID));
// Write the Message (4 bytes) at offset 2
Packet.WriteBuffer(2, Packet.StringToBytes(Message));
// You can also write single bytes directly
Packet.Item[6] := $FF; // Write byte 255 at offset 6
// ... now the Packet buffer can be sent
// MySocket.Send( Packet.ToBytes() );
finally
Packet.Free;
end;
end;