1

你好,我有这个打包的记录:

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 ?

非常感谢

4

2 回答 2

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

于 2013-07-01T20:21:33.203 回答
0

为什么不持有

StreamHolder: Byte;

作为

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 ;
于 2013-07-02T06:44:45.920 回答