When I try to pass tmemorystream as a var or pointer to a procedure it comes back corrupted. What is the proper way to do this?
For example:
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;
You don’t create
datawithin this method. As it is a var (byref) parameter, I would expect it to be created withintform1.downloadmemupdate, i.e.:Note that if you create an object like this, you will need to free it somewhere else, probably in the calling code.
e.g.
An alternative (and the idiomatic method in Delphi) is to pass objects by value (without the var). and leave it to the calling code to create and destroy them. This is mainly because Delphi doesn’t have garbage collection, so it forces the person writing the calling code to think about “ownership”.
This would be
calling code: