Mega Code Archive

 
Categories / Delphi / COM
 

Binary Streaming over COMDCOM

Title: Binary Streaming over COM/DCOM Question: How can I send a binary file through COM/DCOM? Answer: Two functions which can be used to stream a binary file or binary data over COM or DCOM using an OleVariant as the COM medium of binary transfers: type TByteArray = array of byte; //******************************************************************// // OleVariantToStream * // * // Inserts an OleVariant to a TStream (COM Compatible) * //****************************************************************** procedure OleVariantToStream(var Input: OleVariant; Stream: TStream); var pBuf: Pointer; begin pBuf := VarArrayLock(Input); Stream.Write(TByteArray(pBuf^), Length(TByteArray(Input))); VarArrayUnlock(Input); end; //****************************************************************** // StreamToOleVariant * // * // Copies a TStream contents of Count bytes based on the current Position * // to an OleVariant (COM Compatible) * //****************************************************************** function StreamToOleVariant(Stream: TStream; Count: Integer): OleVariant; var pBuf: Pointer; begin Result := VarArrayCreate([0, Count-1], varByte); pBuf := VarArrayLock(Result); Stream.Read(TByteArray(pBuf^), Length(TByteArray(Result))); VarArrayUnlock(Result); end; To implement these functions, say you have a COM method to store a file: procedure StoreFile(FileContents: OleVariant); var FS: TFileStream; begin FS := TFileStream.Create('some file name', fmCreate or fmOpenWrite or fmShareExclusive); OleVariantToStream(FileContents, FS); FS.Free; end; pretty simple, eh?... To call StoreFile on the client side you would do something like this.. procedure SendFileToServer(FileName: string); var FS: TFileStream; begin FS := TFileStream.Create(FileName, fmOpenRead or fmShareCompatible); MyServer.StoreFile(StreamToOleVariant(FS, FS.Size)); FS.Free; end; also, pretty simple.. Have fun!