Не удается получить результат асинхронной операции (интерфейс Windows :: Foundation :: IAsyncOperation) в C ++ WinRT - PullRequest
0 голосов
/ 23 мая 2018

Я немного отчаянно пытаюсь получить результат асинхронного метода winrt с Windows::Foundation::IAsyncOperation интерфейсом.Проект представляет собой проект Visual Studio Community 2017 c ++ с включенным расширением winRT.Я пытался использовать функции std::future / co_await, а также метод задачи, но вызов GetResults() всегда генерировал исключение "вызов в неожиданное время".

С помощью следующего кода я не получаюисключение, но GetResults() возвращает nullptr.Я также пытался объявить async_op как shared_ptr auto async_op = std::make_shared<Windows::Foundation::IAsyncOperation<Windows::Devices::Bluetooth::BluetoothLEDevice^> ^> и получить к нему доступ с помощью *async_op в коде Handler, но я получаю тот же результат.

Любые идеи будут приветствоваться.

Заранее спасибо.

void BleEnumeration::PerformConnectDevice(std::string* bleDevId)
{               
    std::wstring bleDevId_w_str = std::wstring((*bleDevId).begin(), (*bleDevId).end());
    const wchar_t* bleDevId_w_char = bleDevId_w_str.c_str();
    Platform::String^ bleDevId_refStr = ref new Platform::String(bleDevId_w_char);

    auto async_op = Windows::Devices::Bluetooth::BluetoothLEDevice::FromIdAsync(bleDevId_refStr);
    async_op->Completed = ref new Windows::Foundation::AsyncOperationCompletedHandler<Windows::Devices::Bluetooth::BluetoothLEDevice^>(
        [async_op] (Windows::Foundation::IAsyncOperation< Windows::Devices::Bluetooth::BluetoothLEDevice^ >^ operation, Windows::Foundation::AsyncStatus status)
        {
            if (async_op->Status == Windows::Foundation::AsyncStatus::Completed)
            {
                auto bleDevTest = async_op->GetResults();
            }
        });
}

1 Ответ

0 голосов
/ 24 мая 2018

Я заставил это работать:

Windows::Devices::Bluetooth::BluetoothLEDevice^ BleEnumeration::getBleDevice(Windows::Foundation::IAsyncOperation<Windows::Devices::Bluetooth::BluetoothLEDevice^>^ async)
{
    if ((async)->Status != Windows::Foundation::AsyncStatus::Completed)
    {       
        HANDLE signal = CreateEvent(nullptr, true, false, nullptr);
        (async)->Completed = ref new Windows::Foundation::AsyncOperationCompletedHandler<Windows::Devices::Bluetooth::BluetoothLEDevice^>(
            [&signal](Windows::Foundation::IAsyncOperation< Windows::Devices::Bluetooth::BluetoothLEDevice^ >^ operation, Windows::Foundation::AsyncStatus status)
        {
            SetEvent(signal);
        });
        WaitForSingleObject(signal, INFINITE);
    }
    Windows::Devices::Bluetooth::BluetoothLEDevice^ device = async->GetResults();
    return device;
}

bool BleEnumeration::PerformConnectDevice(std::string* bleDevId)
{
    bool success = false;
    Windows::Devices::Bluetooth::BluetoothLEDevice^ bleDevTest = nullptr;

    std::wstring bleDevId_w_str = std::wstring((*bleDevId).begin(), (*bleDevId).end());
    const wchar_t* bleDevId_w_char = bleDevId_w_str.c_str();
    Platform::String^ bleDevId_refStr = ref new Platform::String(bleDevId_w_char);
    Windows::Foundation::IAsyncOperation<Windows::Devices::Bluetooth::BluetoothLEDevice^>^ asyncOp = Windows::Devices::Bluetooth::BluetoothLEDevice::FromIdAsync(bleDevId_refStr);      
    bleDevTest = getBleDevice(asyncOp);

    if (bleDevTest != nullptr)
    {
        success = true;
    }
    return success;
}

И причина, по которой GetResults () дала nullptr, заключалась в следующем: Включить возможность в appxmanifest

Все необходимые возможности должныбыть включенным в файле Package.appxmanifest проекта Visual Studio, в моем случае: «Bluetooth».Я заметил, что получаю ошибку: onecoreuap\drivers\wdm\bluetooth\user\winrt\device\bluetoothledevice.cpp(728)\Windows.Devices.Bluetooth.dll!00007FFC1601AE2F: (caller: 00007FFC1602081A) Exception(1) tid(212c) 80070005 Access is denied.

...