我正在探索并尝试学习 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 lib 但这不是必需的,除非通过这样做包装器的实现变得更加简单。问题是我无法弄清楚如何实现包装器。
最佳答案
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);
}
}
这应该做你想做的。
关于c++ - 将需要回调的函数调用转换为协程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64270626/