如何在c++/WRL上执行与C# async wait相同的操作

问题描述 投票:0回答:1

我正在尝试c ++ / WRL,但我没有做基础知识,主要是调用异步函数并获取结果,例如如何获取以下代码返回的IStorageFile:

HString path;
path.Set(L"C:\\somepath\\somefile.txt");

// Get the Activation Factory
ComPtr<IActivationFactory> pStorageFileActivationFactory;
hr = GetActivationFactory(HStringReference(RuntimeClass_Windows_Storage_StorageFile).Get(), &pStorageFileActivationFactory);
if (FAILED(hr))
{
    return PrintError(__LINE__, hr);
}
ComPtr<IStorageFileStatics> pStorageFileStatics;
hr = pStorageFileActivationFactory.As(&pStorageFileStatics);

__FIAsyncOperation_1_Windows__CStorage__CStorageFile* filePathStorage;
hr = pStorageFileStatics->GetFileFromPathAsync(path.Get(), &filePathStorage);

我如何执行 filePathStorage IAsyncOperation 对象?我怎样才能在 C++/WRL 中做到这一点?

c# c++ asynchronous wrl
1个回答
0
投票

获取文件的 IStorageFile - 等待 GetFileFromPathAsync。

#include <cassert>
#include <condition_variable>
#include <mutex>
#include <wrl.h>

#include <windows.foundation.h>
#include <windows.storage.h>

using namespace Microsoft::WRL;
using namespace Microsoft::WRL::Wrappers;

using namespace ABI::Windows::Foundation;
using namespace ABI::Windows::Storage;

int main(int argc, char** argv)
{
    HRESULT hr = S_OK;

    RoInitialize(RO_INIT_MULTITHREADED);

    HString path;
    path.Set(L"C:\\appverifUI.dll");

    ComPtr<IActivationFactory> pStorageFileActivationFactory;
    hr = GetActivationFactory(HStringReference(RuntimeClass_Windows_Storage_StorageFile).Get(), &pStorageFileActivationFactory);

    ComPtr<IStorageFileStatics> pStorageFileStatics;
    hr = pStorageFileActivationFactory.As(&pStorageFileStatics);

    ComPtr<IAsyncOperation<StorageFile*>> op;
    hr = pStorageFileStatics->GetFileFromPathAsync(path.Get(), &op);

    std::mutex m;
    std::condition_variable cv;
    ComPtr<IStorageFile> isf;

    op->put_Completed(Callback<IAsyncOperationCompletedHandler<StorageFile*>>([&m, &cv, &isf](IAsyncOperation<StorageFile*>* args, AsyncStatus status) {
        {
            std::unique_lock<std::mutex>(m);
            args->GetResults(isf.GetAddressOf());
        }
        cv.notify_all();
        return S_OK;
    }).Get());

    {
        std::unique_lock<std::mutex> ul(m);
        cv.wait(ul, [&isf]() { return !!isf; });
    }

    HSTRING ftype;
    hr = isf->get_FileType(&ftype);

    assert(hr == S_OK);

    return 0;
}
© www.soinside.com 2019 - 2024. All rights reserved.