Sunday, April 23, 2006
Serialization in Delphi
One of the few visitors to this site came here looking to learn how to do serialization in Delphi, so I thought I'd oblige. Fire up Delphi, create a new Windows Application project and add a button and a memo control to the form. In the event handler for the button, add some code as follows- procedure TForm1.Button1Click(Sender: TObject); var LStream : TMemoryStream; begin LStream := TMemoryStream.Create(); LStream.WriteComponent(Memo1); LStream.Position := 0; Memo1.Text := ''; LStream.ReadComponent(Memo1); LStream.Free; end; Now run it and hit the button and, er, nothing happens, which is exactly as it should be. This just shows that the memo control is getting serialized to the stream, the text in the memo is getting cleared, and then the memo is getting deserialized and the text is getting put back. And that is about all there is to it. To add a bit of excitement, add another button and another memo. Add the following code to the event handler for the new button- procedure TForm1.Button2Click(Sender: TObject); var LStream : TMemoryStream; LStringStream : TStringStream; begin LStream := TMemoryStream.Create(); LStream.WriteComponent(Memo1); LStream.Position := 0; LStringStream := TStringStream.Create(''); ObjectBinaryToText(LStream, LStringStream); Memo2.Text := LStringStream.DataString; end; By default, Delphi serializes objects in a binary format. The ObjectBinaryToText method converts it to a human-readable form and there is another method to go the other way. Recognize the text format? It's the same as Delphi uses for storing DFMs. The serialization support in Delphi was developed purely for the IDE, which is why it's only really a half-arsed implementation. The only properties that will be serialized are published ones, which will likely limit what you can do with it. Of course, there are all the problems with serialization you should consider before you start using it. There's a whole lot more to serialization than this, but I hope this has been a useful introduction.