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.
Want to see what's in a stream? Convert it to the text format used in modern .dfm files:
- 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:
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...
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.
The link here don't work. why TPersistent is not worth it?
I cannot remember the problems I anticipated. You are right that the link is now dead.
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.
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
Post a Comment
<< Home