Search code examples
delphimemory-managementstreamvariant

How can I assign a value to a Olevariant variable which comes from a TStream?


I need to read from a Stream and put the buffer that was read in a OleVariant (VarArray) variable.

var
MemoryStream : TMemoryStream;
Data : OleVariant;
begin
            MemoryStream:=TMemoryStream.Create;
            try
                FuncFill(MemoryStream); //Filling the stream
                MemoryStream.Seek(0,0);
                MemoryStream.Read(Data, MemoryStream.Size);//this line lock the app, I need allocate the memory for the OleVariant variable?
            finally
             MemoryStream.Free;
            end;

end;

How I can assign the read value from the TMemoryStream to a olevariant variable?

I'm using delphi 5.


Solution

  • You can use the VarArrayLock function to get a pointer to the OleVariant data and then read to this pointer.

    check this code wich use a VarArray of varByte elements.

    var
     MemoryStream : TMemoryStream;
     Data : OleVariant;
     DataPtr : Pointer;
    begin
       MemoryStream:=TMemoryStream.Create;
         try
          FuncFill(MemoryStream); //Filling the stream
          MemoryStream.Seek(0,0);
              Data    :=VarArrayCreate([0, MemoryStream.Size - 1], varByte);
          DataPtr     :=VarArrayLock(Data);
           try
             MemoryStream.ReadBuffer(DataPtr^,MemoryStream.Size); //Get the pointer to the variant variable.
           finally
             VarArrayUnlock(Data); //when you are done , you must call to VarArrayUnlock
           end;
        finally
          MemoryStream.Free;
        end;    
    end;