简体   繁体   English

delphi将MemoryStream复制到动态数组

[英]delphi Copy MemoryStream to Dynamic array

Hello please i've this packed record : 你好,我有这个包装记录:

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

// i would like to save the MemoryStream into the StreamHolder please see my below procedure: //我想将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;

So please how could i copy the Strm to the StreamHolder ? 那么请问我如何将Strm复制到StreamHolder?

many thanks 非常感谢

You appear to want to copy the entire stream onto @MyRecord.StreamHolder . 您似乎想要将整个流复制到@MyRecord.StreamHolder Do that like this: 这样做:

Strm.ReadBuffer(MyRecord.StreamHolder, Size);

You'll also need to change your GetMem to allocate enough memory. 您还需要更改GetMem以分配足够的内存。

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

Or perhaps more elegantly: 或者更优雅:

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

As it stands your code does not take account of that part of the record which appears before StreamHolder . 目前,您的代码不会考虑在StreamHolder之前出现的记录部分。

Why not holding 为什么不抱着

StreamHolder: Byte;

as

StreamHolder: tMemoryStream;

and change the procedure to 并将过程更改为

 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 ;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM