delphi将MemoryStream复制到动态数组

时间:2013-07-01 20:11:41

标签: delphi delphi-7

你好,我有这个包装记录:

type
 TMyRecord = packed record
    BufSize: Word;
    TargetUser:array[0..80] of char;
    StreamHolder: Byte;
  end;
  PMyRecord = ^TMyRecord;

//我想将MemoryStream保存到StreamHolder中 请参阅我的以下程序:

Procedure AddToRec(ATargetUser:String);
var
MyRecord: PMyRecord;
Strm:TMemoryStream;
Size: Integer;
begin
Strm:=TMemoryStream.Create;
try
Strm.LoadFromFile('myFile.dat');
Strm.position:=0;
Size:=Strm.size;
GetMem(MyRecord,Size);
ZeroMemory(MyRecord,Size);
MyRecord.BufSize := Size;
StrCopy(MyRecord.TargetUser,PChar(ATargetUser));

// here how could i copy the Strm into the StreamHolder ?

//SendMyBuffer(MyRecord,Size);

finally
Strm.free;
end;
end;

那么请问我如何将Strm复制到StreamHolder?

非常感谢

2 个答案:

答案 0 :(得分:3)

您似乎想要将整个流复制到@MyRecord.StreamHolder。这样做:

Strm.ReadBuffer(MyRecord.StreamHolder, Size);

您还需要更改GetMem以分配足够的内存。

GetMem(MyRecord, Size + SizeOf(MyRecord^) - SizeOf(MyRecord.StreamHolder));

或许更优雅:

GetMem(MyRecord, Size + Integer(@PMyRecord(nil)^.StreamHolder));

目前,您的代码未考虑StreamHolder之前显示的记录部分。

答案 1 :(得分:0)

为什么不举行

StreamHolder: Byte;

as

StreamHolder: tMemoryStream;

并将程序更改为

 var
   MyRecord: PMyRecord;
 begin
   GetMem(MyRecord,SizeOf(pMyRecord));
   myRecord.StreamHolder := TMemoryStream.Create;
   try
    myRecord.StreamHolder.LoadFromFile('myFile.dat');
    //Strm.position:=0;
    //Size:=Strm.size;
    //ZeroMemory(MyRecord,Size);
    //MyRecord.BufSize := Size;
    StrCopy(MyRecord.TargetUser,PChar(ATargetUser));
   finally 
     // no free in here... free the streamholder whenever you get rid of MyRecord...
   end ;