c++ - 将需要回调的函数调用转换为协程

标签 c++ c++20 c++-coroutine

我正在探索并尝试学习 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 &parameter)
               :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/

相关文章:

c++ - 从非托管代码更新性能计数器

c++ - 如何将 'CDT' 转换为 time_zone_ptr

c++ - std::invocable 和 std::regular_invocable 概念之间有什么区别?

c++ - 传递给协程的临时对象何时被销毁?

外部服务器的 C++ 客户端和外部客户端的服务器与 boost::asio 协程同时使用

c++ - 元组在 VS2012 中如何工作?

c++ - 类上的行外定义错误,但它在头文件中声明

c++ - 有什么方法可以避免为这个 C++ 范围的记录器使用宏?

c++ - 我可以编写一个需要函数模板的 C++ 概念吗?必须向该函数模板提供一些枚举值作为模板参数?