问题
Hi I have defined some records in my project which may be consisted of other records and also dynamic arrays of normal data types and other records , it is n example of a record type
Type1=record
x:integer;
end;
Type2=record
Y:array of X;
str:string;
end;
When I tried to save one of variables of these records type to file with blockwrite function like this :
var
Temp1:Type2;
begin
setlength(temp1.y,100);
blockwrite(MyFile,Temp1,sizeOf(Temp1);
it just wrote as much as the size of pure record is ,but temp1 has a dynmic arrays which is resized , Could someone please tell me how I can write a complex record to a file , I mean something like what is used in VB6 . Thanks
回答1:
You can use https://github.com/KrystianBigaj/kblib (works with any dynamic records, also records that contains other records, etc.). Tested on Delphi 2006/2009/XE (it doesn't use extended RTTI introduced in D2010). No need to write save/load code manually (just one line to save/load any dynamic type - strings, records, dynamic arrays).
In your example it would be sth. like this:
TKBDynamic.WriteTo(lStream, lType2, TypeInfo(Type2));
To load it back:
TKBDynamic.ReadFrom(lStream, lType2, TypeInfo(Type2));
If anyone is interested how to deal with 'record versions', just post new issue and then I'll write some examples.
Similar questsion:
- How Can I Save a Dynamic Array to a FileStream in Delphi?
- Delphi 2010: How to save a whole record to a file?
回答2:
This won't work. You will need to manually write (streaming) code to write every field.
Have a look at published fields/properties in classes, since together with arrays of variants, this used to be the only way to stream data using generic code.
However since D2010 the RTTI was expanded, but I don't know the exact details of that yet.
来源:https://stackoverflow.com/questions/4533376/writing-complex-records-to-file