Saving VirtualStringTree Node Data

I am trying to move a project from D6 to D-XE3. I am getting garbage when saving and loading the tree data in the OnSaveNode and OnLoadEvents using version 5.10 of VirtualStringTree. I'm probably not handling Unicode correctly, but there could be some other ignorance on my part:

procedure TfMain.vstGridSaveNode(Sender: TBaseVirtualTree; Node: PVirtualNode;
  Stream: TStream);
var
  Data: PStkData;
begin
  Data := Sender.GetNodeData(Node);

  //  Owned: boolean;
  Stream.Write(Data.Owned, SizeOf(boolean) );

  //  Symbol: string;
  Stream.Write(PChar(Data.Symbol)^, Length(Data.Symbol) * SizeOf(Char));

  //  AvgTarget: currency;
  //Stream.Write(Data.AvgTarget, SizeOf(currency));

  //  PE: double;
  Stream.Write(Data.PE, SizeOf(double));
end;

procedure TfMain.vstGridLoadNode(Sender: TBaseVirtualTree; Node: PVirtualNode;
  Stream: TStream);
var
  Data: PStkData;
begin
  Data := Sender.GetNodeData(Node);

  //Owned: boolean;
  Stream.Read(Data.Owned, SizeOf(boolean));

  //Symbol: string;
  Stream.Read(PChar(Data.Symbol)^, Length(Data.Symbol) * SizeOf(Char));

  //AvgTarget: currency;
  Stream.Read(Data.AvgTarget, SizeOf(currency));

  //PE: double;
  Stream.Read(Data.PE, SizeOf(double));
end;

Thanks for any help.


When you write the character data, you need to make sure you write it in such a way that you know how much to read again while loading. You're currently writing just the character data, so you have no idea how much you need to read again later. You're instead assuming that Symbol will already be the right length, which, now that I've pointed it out, is something you probably realize is an invalid assumption.

When you write the string, first write its length so it will be available to read while loading:

var
  SymbolLen: Integer;

SymbolLen := Length(Data.Symbol);
Stream.Write(SymbolLen, SizeOf(SymbolLen));
Stream.Write(PChar(Data.Symbol)^, Length(Data.Symbol) * SizeOf(Data.Symbol[1]));

Then you can read it:

Stream.Read(SymbolLen, SizeOf(SymbolLen));
SetLength(Data.Symbol, SymbolLen);
Stream.Read(PChar(Data.Symbol)^, SymbolLen * SizeOf(Data.Symbol[1]));
链接地址: http://www.djcxy.com/p/35070.html

上一篇: 带有隐藏节点的Color VirtualStringTree行

下一篇: 保存VirtualStringTree节点数据