Search code examples
c++c++20c++-coroutine

Wrap Callback API into Coroutine-based Iterable


I want to warp a typical C callback API that generates multiple int values into an iterable in the fashion of std::generator<int> (see p2502r1).

API looks like:

typedef void (*Callback)(int);
void api(Callback callback) {
   callback(1);
   callback(2);
   callback(3);
}

The API wrapper should behave like:


for(int i : APIWrapper(&api)){
   std::cout << i << std::endl;
}

expected result:

1
2
3

I've been looking into this but couldn't figure out how to extend it accordingly:

I am looking for leads how to accomplish what is described above.


Solution

  • What you want isn't really possible with co_await-style coroutines. To do this, you would need to be able to suspend within the callback such that it also suspends the api function as well. co_await-style coroutines can't do that.