Board index » delphi » TMemoryStream problem?

TMemoryStream problem?

Hi,
        Can any one please tell me what is the problem with the following code!

procedure TForm1.Button1Click(Sender: TObject);
var
   dwMaxSize : DWORD;
   hBuf : HGLOBAL;
   Buffer : Pointer;
   stream : TMemoryStream;
   dwActualSize : DWORD;
   dwSize : DWORD;

begin
        .
        .
        .

         hBuf := GlobalAlloc(GHND, dwMaxSize);
         Buffer := GlobalLock(hBuf);
        .
        .
        .
         stream := TMemoryStream.Create;
         stream.WriteBuffer(Buffer, dwMaxSize); <<-------PROBLEM
         stream.Seek(soFromBeginning, 0);
         lbs_blob.LoadFromStream(stream);
         stream.Free;
         GlobalUnlock(hBuf);
         GlobalFree(hBuf);
        .
        .
        .
end;

        In the above piece of code, the program crashes (gives an Access
violation) if the dwMaxSize > 5000. WHYYYY!??? I am totally bewildered!
TIA

Soumik.

 

Re:TMemoryStream problem?


Quote
Soumik Sarkar wrote:

> Hi,
>         Can any one please tell me what is the problem with the following code![...]
>          hBuf := GlobalAlloc(GHND, dwMaxSize);
>          Buffer := GlobalLock(hBuf);[...]
>          stream.WriteBuffer(Buffer, dwMaxSize); <<-------PROBLEM[...]
>         In the above piece of code, the program crashes (gives an Access
> violation) if the dwMaxSize > 5000. WHYYYY!??? I am totally bewildered!

        Well, the reason it doesn't work is that WriteBuffer takes a variable
as a parameter, not a pointer to the variable. So the code above is trying
to read dwMaxSize bytes from the 4-byte variable Buffer - you'd complain to.
You can "fix" this by saying

stream.WriteBuffer(Buffer^, dwMaxSize);

        There's really no reason I can see that you should be fooling with
the Windows memory-allocation stuff this way, btw - you should be able to
do the same thing with GetMem or AllocMem. Also you may want to look at
the docs on the Write method - could be you want that instead of WriteBuffer.

--
David Ullrich

?his ?s ?avid ?llrich's ?ig ?ile
(Someone undeleted it for me...)

Other Threads