Saving VirtualStringTree Node Data

妖精的绣舞 提交于 2019-12-11 02:37:46

问题


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.


回答1:


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]));


来源:https://stackoverflow.com/questions/14713885/saving-virtualstringtree-node-data

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!