传递一个tmemorystream作为var

时间:2012-11-06 05:18:45

标签: delphi pointers procedure var

当我尝试将tmemorystream作为var或指向程序的指针传递时,它会被损坏。这样做的正确方法是什么?

例如:

function tform1.downloadmemupdate(url, desc: string; var data: tmemorystream; var msg: string): boolean;
begin
  filelabel.Caption:=desc;
  downloadmemthread:=tdownloadmemthread.create(url);
  dlcancelbtn.Enabled:=true;
  downloadmemthread.dlstart;
  waitforsingleobject(downloadmemthread.Handle, INFINITE);

  downloadmemthread.data.SaveToStream(data); //corrupted
  downloadmemthread.data.SaveToFile('data.zip');  //works

  dlcancelbtn.Enabled:=false;
  result:=not (downloadmemthread.canceled and downloadmemthread.success);
  dlcanceled:=downloadmemthread.canceled;
  msg:=downloadmemthread.msg;
  downloadthread.Free;
end;

1 个答案:

答案 0 :(得分:5)

您不在此方法中创建data。由于它是一个var(byref)参数,我希望它可以在tform1.downloadmemupdate内创建,即:

data := TMemoryStream.Create;

请注意,如果您创建这样的对象,则需要将其释放到其他位置,可能是在调用代码中。

e.g。

   Data := nil;
   try
     downloadmemupdate(url, desc, data, msg);
     // do something with data
   finally
     Data.Free;
   end;  

另一种选择(以及Delphi中的惯用方法)是按值传递对象(不带var)。并将其留给调用代码来创建和销毁它们。这主要是因为Delphi没有垃圾收集,所以它迫使编写调用代码的人思考“所有权”。

这将是

function tform1.downloadmemupdate(url, desc: string; data: TStream; var msg: string): boolean;
begin
  filelabel.Caption:=desc;
  downloadmemthread:=tdownloadmemthread.create(url);
  try
    ...
    downloadmemthread.data.SaveToStream(data); //corrupted
    downloadmemthread.data.SaveToFile('data.zip');  //works    
  finally
    downloadmemthread.Free;
  end;

end;

调用代码:

   Data := TMemoryStream.Create;
   try
     downloadmemupdate(url, desc, data, msg);
     // do something with data
   finally
     Data.Free;
   end;