Delphi: Why TStreamAdapter Is Not Suitable for IStream-Based Virtual Files

Artem Razin
May 3, 2010

Hello,

One Delphi programmer once wrote that he tried to create an IStream-based virtual file using TStreamAdapter.
However, it didn't work. Why?

Why TStreamAdapter Doesn't Work

The reason is quite simple: TStreamAdapter doesn't provide a correct implementation of IStream.Clone.

Check the Classes.pas source:

function TStreamAdapter.Clone(out stm: IStream): HResult;
begin
  Result := E_NOTIMPL;
end;

The IStream.Clone method is important — BoxedApp SDK relies on it to duplicate stream handles correctly.
But TStreamAdapter simply returns E_NOTIMPL.

The Solution

You can fix this by creating a new class derived from TStreamAdapter and implementing IStream.Clone.

For example, if you need a TStreamAdapter based on TFileStream, use the following implementation:

type
  TCloneSA = class(TStreamAdapter)
  public
    Path: String;
  public
    function Clone(out stm: IStream): HResult; override; stdcall;
    destructor Destroy; override;
  end;
 
{ TCloneSA }
 
function TCloneSA.Clone(out stm: IStream): HResult;
var
  FS: TFileStream;
  S: TCloneSA;
begin
  FS := TFileStream.Create(Path, fmOpenReadWrite or fmShareDenyNone);
  S := TCloneSA.Create(FS, soOwned);
  S.Path := Path;
 
  Result := S.QueryInterface(IStream, stm);
end;

This version provides a proper Clone implementation that creates a new TFileStream and returns an independent IStream reference — exactly what BoxedApp SDK expects.


To try this in action, use it with BoxedAppSDK_CreateVirtualFileBasedOnIStream and enjoy full compatibility with BoxedApp's virtual file layer.