我正在探索并尝试学习C ++协程(在C ++ 20中添加)。我正在使用的SDK具有异步API调用,这些调用均带有回调,这些回调在SDK管理的某些后台线程上调用。
namespace third_party {
bool api_call(const std::string& some_parameter, const std::function<void(std::error_code)>& callback);
} // namespace third_party
我想将此API调用包装成可以等待的东西:
namespace my_third_party_sdk_wrapper {
cppcoro::task<std::error_code> api_call(const std::string& some_parameter);
cppcoro::task<std::error_code> api_call(const std::string& some_parameter, cppcoro::cancellation_token token);
} // namespace my_third_party_sdk_wrapper
我正在考虑使用cppcoro库,但这不是必需的,除非通过这种方法使包装器的实现变得简单得多。
问题是我不知道如何实现包装器。
雷蒙德·陈(Raymond Chen)有一篇非常好的文章,您可以在这里找到。
就您而言,您可以执行以下操作。
namespace my_third_party_async_sdk_wrapper
{
auto api_call_async(const std::string& some_parameter)
{
struct awaiter : public std::experimental::suspend_always
{
awaiter(const std::string ¶meter)
:parameter_(parmeter) {}
bool await_ready() { return false; }
void await_suspend(std::experimental::coroutine_handle<> handle)
{
// use your third party lib call directly here.
api_call(parameter_, [handle]()
{
// call the handle to resume the coroutine
handle();
}
}
const std::string parameter_;
};
return awaiter(some_parameter);
}
}
这应该做您想要的。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句