Microsoft 信息保护 SDK - 策略 SDK 观察器

策略 SDK 包含一个观察程序类。 重写观察程序的虚成员,以处理异步操作的回调。

异步操作完成后,SDK 将调用 OnXxx() 与结果相对应的成员函数。 例如,对于 OnLoadSuccess() 为 OnLoadFailure()、OnAddEngineSuccess() 和 mip::PolicyProfile::Observer。

以下示例演示了 promise/future 模式。 SDK 示例还使用此模式,并且可以扩展它以实现所需的回调行为。

Profile 观察程序的实现

以下示例创建派生自mip::PolicyProfile::Observer的类ProfileObserver。 成员函数将重写基类,以使用整个示例中使用的未来/承诺模式。

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。

第二个是指向“上下文”的共享指针。 在此实现中,上下文是对 shared_ptr<void> 的引用,并以 std::promise 形式传入。 函数的第一行将此值强制转换为 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

执行任何异步操作时,将观察程序实现传递给设置构造函数或异步函数本身。

后续步骤