Search code examples
visual-c++uwpc++-winrt

Please advise how for ReadAsync by C++/WinRT


I'm trying to find StorageFile's OpenAsync, ReadAsync for C++/WinRT very difficult. ( and tried testing with C# in UWP, it passed no problem. I originally developed with C++ MFC. )

Windows::Foundation::IAsyncAction MainPage::FilePickerAsync()
{
    auto picker = FileOpenPicker();

    picker.ViewMode( PickerViewMode::List );

    picker.FileTypeFilter().Append( L".cpp" );

    StorageFile file = co_await picker.PickSingleFileAsync();

    try
    {
            IRandomAccessStream stream = co_await file.OpenAsync( FileAccessMode::Read );

            uint64_t size64 = stream.Size();                                        // <= Error

            uint32_t size32 = static_cast< uint32_t >( size64 ); 

            auto buffer = Buffer( size32 );

            co_await stream.ReadAsync( buffer, size32, InputStreamOptions::None );  // <= Error

            stream.Close(); 
    }
    catch ( const hresult_error &ex )
    {
    }
}   

Visual C++ 2019

Error C3779 'winrt::impl::consume_Windows_Storage_Streams_IRandomAccessStream <winrt::Windows::Storage::Streams::IRandomAccessStream>::Size': a function that returns 'auto' cannot be used before it is defined

Error C3779 'winrt::impl::consume_Windows_Storage_Streams_IInputStream<< D >>::ReadAsync': a function that returns 'auto' cannot be used before it is defined


Solution

  • a function that returns 'auto' cannot be used before it is defined

    As @Hans Passant recommend Raymond Chen's blog,

    And the key point is that the forward-declared methods are declared as returning auto with no trailing return type and no body. This means “I want the compiler to deduce the return type (but I’m not giving any clues yet).” If you try to call the method before the method has been implemented, then the compiler reports an error because it doesn’t yet have the necessary information to determine the return type.

    You need add the specific head file then add the namespace in your main page class like the following.

    pch file

      include <winrt/Windows.Storage.Pickers.h>
      include <winrt/Windows.Storage.Streams.h>
    

    MainPage namespace

    using namespace Windows::Storage::Pickers;
    using namespace Windows::Storage::Streams;
    using namespace Windows::Storage;