Microsoft 資訊保護 SDK - 原則 SDK 觀察者

Policy SDK 包含一個觀察者類別。 覆蓋虛擬觀察者成員以處理非同步操作的回調。

當非同步操作完成時,SDK 會呼叫 OnXxx() 對應結果的成員函式。 範例包括OnLoadSuccess()、OnLoadFailure()和OnAddEngineSuccess()用於mip::PolicyProfile::Observer。

以下範例展示了承諾與未來的模式。 SDK 範例也使用這個模式,你可以擴展它來實現想要的回調行為。

設定檔觀察器實作

以下範例會產生一個類別 ,該類別 ProfileObserver由 衍生 mip::PolicyProfile::Observer出。 這些成員函式會覆寫基底類別中的對應函式,以使用整個範例中一貫採用的 Future/Promise 模式。

Note

以下範例僅實作觀察者類別的一部分,且不包含與 mip::PolicyEngine 相關之觀察者的覆寫。

profile_observer.h

標頭檔定義了 ProfileObserver,使其衍生自 mip::PolicyProfile::Observer,然後覆寫每一個成員函式。

class ProfileObserver final : public mip::PolicyProfile::Observer {
public:
ProfileObserver() { }
  void OnLoadSuccess(const std::shared_ptr<mip::PolicyProfile>& profile, const std::shared_ptr<void>& context) override;
  void OnLoadFailure(const std::exception_ptr& error, const std::shared_ptr<void>& context) override;
  //TODO: Implement remaining members
};

profile_observer.cpp

實作會為每個觀察者成員函式定義所要採取的動作。

每個成員都接受兩個參數。 第一個是指向函式所處理類別的共享指標。 ProfileObserver::OnLoadSuccess 預期接收 mip::PolicyProfile。 ProfileObserver::OnAddEngineSuccess 需要 mip::PolicyEngine。

第二種是指向 上下文 的共享指標。 在此實作中,內容脈絡是對 std::promise 的參考,並作為 shared_ptr<void> 傳入。 函數的第一行將此值 std::promise鑄造成 ,然後將其儲存在一個稱為 promise的物件中。

最後,程式碼透過設定 promise->set_value() 並傳遞 mip::PolicyProfile 物件,讓未來做好準備。

#include "profile_observer.h"
#include <future>

//Called when Profile is successfully loaded
void ProfileObserver::OnLoadSuccess(const std::shared_ptr<mip::PolicyProfile>& profile, const std::shared_ptr<void>& context) {
  //cast context to promise
  auto promise = std::static_pointer_cast<std::promise<std::shared_ptr<mip::PolicyProfile>>>(context);
  //set promise value to profile
  promise->set_value(profile);
}

//Called when Profile fails to load
void ProfileObserver::OnLoadFailure(const std::exception_ptr& error, const std::shared_ptr<void>& context) {
  auto promise = std::static_pointer_cast<std::promise<std::shared_ptr<mip::PolicyProfile>>>(context);
  promise->set_exception(error);
}

//TODO: Implement remaining observer members

當你執行任何非同步操作時,將觀察者實作傳給設定建構子或非同步函式本身。

下一步