数据流转换,com入门坎(200分)

  • 主题发起人 主题发起人 yanlei
  • 开始时间 开始时间
Y

yanlei

Unregistered / Unconfirmed
GUEST, unregistred user!
function StreamToVariant(Stream: Tstream): OleVariant;
var
p: Pointer;
begin
Result := VarArrayCreate([0, Stream.Size - 1], varByte);
p := VarArrayLock(Result);
try
Stream.Position := 0; //start from beginning of stream
Stream.Read(p^, Stream.Size);
finally
VarArrayUnlock(Result);
end;
end;
function VariantToStream(const Data: OleVariant): Tstream;
var
p: Pointer;
Stream: Tstream;
begin
p := VarArrayLock(Data);
try
Stream := TMemoryStream.Create;
Stream.Write(p^, VarArrayHighBound(Data, 1) + 1);
finally
VarArrayUnlock(Data);
end;
Result := Stream;
end;

procedure TForm1.Button8Click(Sender: TObject);
const FileName = 'c:/e.txt';
var
FileStream: TFileStream;
v: OleVariant;
newFileStream: Tstream;
LastFileStream: TFileStream;
begin
FileStream := TFileStream.Create(FileName, fmOpenRead);
showmessage(format('%d', [FileStream.Size]));

try
v := StreamToVariant(FileStream);
newFileStream := VariantToStream(v);

LastFileStream := TFileStream.Create('c:/e1.txt', fmCreate or
fmOpenWrite);
//拷贝BLOB到临时文件
showmessage(format('%d', [newFileStream.Size]));
LastFileStream.CopyFrom(newFileStream, newFileStream.Size); //这里错误
//释放流
LastFileStream.Free;

finally
FileStream.Free;
end;

end;

newFileStream.Size的大小是正确的,不能copy数据,是什么原因
 
newFileStream.Position := 0 ; // 加这句
LastFileStream.CopyFrom(newFileStream, newFileStream.Size);
 

Similar threads

后退
顶部