C++ Converting ComPtr<IRandomAccessStream> to ComPtr<IClosable>

When using WRL, sometimes if you have a pointer to derived interface such as IRandomAccessStream (which derives from IClosable), and you would want to convert it to IClosable (so that you can call "Close" on the stream). To do that you will have to use ComPtr.As call.


 WRL::ComPtr< Streams::IRandomAccessStream > randomAccessStream;
// set randomAccessStream to something here.

WRL::ComPtr< IClosable > pICloseable;
HRESULT hr = randomAccessStream.As< IClosable >( &pICloseable );
if( SUCCEEDED( hr ) )
pICloseable->Close(); // Call Close on Stream
Comments (1)
  1. Anonymous says:

    This technique is, of course, the generic method for converting a derived interface to a parent interface.  At one point I had an ABI::Windows::Storage::IStorageFile interface pointer and needed to get its parent ABI::Windows::Storage::IStorageItem interface to call the get_Path() function.  Your method above works here as well:

    ComPtr<IStorageItem> pStorageItem;

    ComPtr<IStorageFile> x(pStorageFile);

    hr = x.As(&pStorageItem);

    (*) Create a ComPtr<ABI::Windows::Storage::IStorageFile> COM pointer, call it x

    (*) Assign the existing IStorageFile pointer to it

    (*) Get the IStorageItem interface pointer by calling As(pStorageItem)

Comments are closed.

Skip to main content