2

我正在尝试将项目从 D6 移动到 D-XE3。使用 VirtualStringTree 5.10 版本在 OnSaveNode 和 OnLoadEvents 中保存和加载树数据时出现垃圾。我可能没有正确处理 Unicode,但我可能还有其他一些无知:

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;

谢谢你的帮助。

4

1 回答 1

8

当您写入字符数据时,您需要确保以您知道在加载时再次读取多少的方式写入它。你目前写字符数据,所以你不知道以后需要再读多少。相反,您假设这Symbol已经是正确的长度,现在我已经指出,您可能意识到这是一个无效的假设。

写入字符串时,首先写入其长度,以便在加载时可以读取:

var
  SymbolLen: Integer;

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

然后你可以阅读它:

Stream.Read(SymbolLen, SizeOf(SymbolLen));
SetLength(Data.Symbol, SymbolLen);
Stream.Read(PChar(Data.Symbol)^, SymbolLen * SizeOf(Data.Symbol[1]));
于 2013-02-05T18:26:18.550 回答