如何解决将需要回调的函数调用转换为协程
我正在探索并尝试学习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)有一篇非常不错的文章,您可以找到here。
根据您的情况,您可以执行以下操作。
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);
}
}
这应该做您想要的。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。