Thursday, February 17, 2005

Delphi: Stream your objects

Delphi's forms demostrate that it can stream objects to and from files. How can you use this to stream your own objects? It took me a day to blunder through this so I thought I'd share.

  • Derive your objects from TComponent. TPersistent is more trouble than it is worth, but see http://www.undu.com/Articles/990609d.html if you really want to.

  • Register each class that will be saved. e.g.
    initialization
    Classes.RegisterClass(TRichClipboardContent);
  • To save an object to a stream:
    stream.WriteComponent(c);
  • Delphi will save your published properties.

  • Override GetChildren in any objects that have sub-objects you want to save.

  • Also override GetChildOwner in such objects, otherwise all objects will be owned by the root component when they are read back in.

  • To read them back in:
    c := stream.ReadComponent(nil);

Want to see what's in a stream? Convert it to the text format used in modern .dfm files:
var
text_stream: TMemoryStream;
terminator: Char;
begin
text_stream := TMemoryStream.Create;
stream.Seek(soFromBeginning, 0);
ObjectBinaryToText(stream, text_stream);
terminator := #0;
debug_stream.Write(terminator, 1); // Add null terminator
OutputDebugString(PChar(debug_stream.Memory));

6 Comments:

Anonymous Anonymous said...

This seems very useful, I've been doing all this manually for quite some time. However, if your objects are going to be modified over time, I'm not sure how to give my file-system backward compatibility as I can if I read and write each property one at a time...

8:39 am  
Blogger Oliver Bock said...

I guess you would need to keep the old versions around as separate classes. Then if you find one of these old classes has been instantiated, convert it to the new class.

8:55 am  
Blogger Roope said...

The link here don't work. why TPersistent is not worth it?

3:07 am  
Blogger Oliver Bock said...

I cannot remember the problems I anticipated. You are right that the link is now dead.

9:38 am  
Anonymous Alex said...

Thanks for your advice. Works great. I'm experimenting with a client / server solution. This seems easier and more straight forward than using Delphi's built in COM solution.

6:50 pm  
Blogger Unknown said...

Hi,

I recently came across your blog and have been reading along. I thought I would leave my first comment. I don't know what to say except that I have enjoyed reading. Nice blog. I will keep visiting this blog very often.

-
Delphi development

6:23 pm  

Post a Comment

<< Home