Question

I'm following this tutorial to the letter for saving and loading my VirtualStringTree: http://wiki.freepascal.org/VirtualTreeview_Example_for_Lazarus My problem now is that when I have saved and loaded, my data is corrupted. Chars are changed and added. So does anyone know what the problem is?

Was it helpful?

Solution

I found this Link and changed the awnser to fit my code.

Data.Symbol[1]  //Simply points to a char. So I changed it to 'char'

Read:

Stream.Read(Len, SizeOf(Len));
SetLength(Data.Column0, Len);
Stream.Read(PChar(Data.Column0)^, Len * SizeOf(Char));

//Copy/Paste this code for all Columns

Write:

Len := Length(Data.Column0);
Stream.Write(Len, SizeOf(Len));
Stream.Write(PChar(Data.Column0)^, Length(Data.Column0) * SizeOf(Char));

//Copy/Paste this code for all Columns

Second answer by TLama:

Read:

var
  TreeData: PTreeData;
  BinaryReader: TBinaryReader;
begin
  TreeData := Sender.GetNodeData(Node);

  BinaryReader := TBinaryReader.Create(Stream);
  try
    TreeData.Column0 := BinaryReader.ReadString;
    TreeData.Column1 := BinaryReader.ReadString;
    TreeData.Column2 := BinaryReader.ReadString;
  finally
    BinaryReader.Free;
  end;
end;

Write:

var
  TreeData: PTreeData;
  BinaryWriter: TBinaryWriter;
begin
  TreeData := Sender.GetNodeData(Node);

  BinaryWriter := TBinaryWriter.Create(Stream);
  try
    BinaryWriter.Write(TreeData.Column0);
    BinaryWriter.Write(TreeData.Column1);
    BinaryWriter.Write(TreeData.Column2);
  finally
    BinaryWriter.Free;
  end;
end;

I implemented TLama's answer because I really can't be bothered with all the pointers. This code looks much better, is a lot easier to read, takes up less space and does the same.

So to conclude. When you search the web for saving your VST data, your gonna get a lot of junk code. The first answer will fix that code for you. The second will make you smile :)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top