C++: callback function with state -


i'm using function of external library written in c (library_function) takes callback function argument. parameters library calls callback function don't matter me. thing i'm interested in order of calls callback function. want callback function return next element of list every time it's called.

consider example:

#include <iostream>  int x; bool *booleans;  void library_function(bool(*callback_fn)()){     (int i=0; < 5; i++) {         std::cout << callback_fn() << std::endl;     } }  bool my_callback_fn(){     return booleans[x++]; }  void my_function(bool b[]){     x = 0;     booleans = b;      library_function(my_callback_fn); }  int main() {     bool booleans[] {true, false, true, true, false};     my_function(booleans); } 

this code works, had use global variables think isn't style.

in python example, use inner function achieve this:

def library_function(callback_fn):     _ in range(5):         print(callback_fn())   def my_function(b):     x = -1      def my_callback_fn():         nonlocal x         x += 1         return b[x]      library_function(my_callback_fn)  if __name__ == '__main__':     booleans = [true, false, true, true, false]     my_function(booleans) 

i've read c++ doesn't support nested functions , lambda functions can used function pointers if not capture variables.

is there way avoid using global variables still being able modify 'internal state' of callback function?

thanks in advance!

i'm using function of external library written in c (library_function) takes callback function argument.

unless external library allows pass user defined context providing callback signature

bool(*callback_fn)(void*)                 // ^^^^^ 

is there way avoid using global variables still being able modify 'internal state' of callback function?

there's no other choice using global context.


Comments

Popular posts from this blog

testing - Detect whether test has failed within fixture -

AbotX : How do you create a parallel crawler that stays on and can be added to at run time from new requests -

android - Create single AAR file from multiple modules using Gradle -