你好,我有这个包装记录:
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?
非常感谢答案 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 ;