2013-07-01 50 views
1

您好請我這個包裝記錄:德爾福複製的MemoryStream到動態數組

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

@大衛赫弗南:StreamHolder:字節;在TMyRecord中聲明 – Sdean

+0

@David Heffernan:我想將流複製到MyRecord但保留StrCopy(MyRecord.TargetUser,PChar(ATargetUser)); – Sdean

回答

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之前出現的創紀錄的那部分。

+0

非常感謝大衛Heffernan爵士,如果我想讀回MyRecord.StreamHolder到流===只是做它Strm.WriteBuffer(?,MyRecord.BufSize); – Sdean

+0

是的,這是基本計劃。 –

+0

如果我想讀回來,應該如何分配內存?請幫助閱讀它*只是MemoryStream *非常感謝 – Sdean

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 ; 
+1

您需要分配BufSize,並調用GetMem傳遞記錄的大小,而不是指向記錄的指針的大小。 –