delphi - 将tmemorystream作为var传递

标签 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;

最佳答案

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

data := TMemoryStream.Create;


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

例如

   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;  

关于delphi - 将tmemorystream作为var传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13244835/

相关文章:

delphi - 我可以使用 generics.defaults 比较 Real48 吗?

delphi - 在 Delphi 中从任务栏隐藏应用程序不起作用

德尔福;向无源控件添加 PopupMenu 支持

C - 返回指向数组的指针

function - 如何查找内部函数的源代码 - gfortran

delphi - 有人有可以将推文上传到 Twitter 的 Delphi 7 代码、类或单元吗?

C语言 : Difference between two ways of pointer assignment

c - 通过指针传递字符串 - 不兼容的参数

MySQL 使用来自另一个表的 like 计数并列出出现次数

mysql - 为什么mysql过程中的if语句无法得到正确的逻辑查询?