简体   繁体   中英

C++ callback with function pointers

I'm writing a C++ application that uses a 3rd party library to open proprietary files. In my application users can do something like this:

int main(int argc, char* argv[]) {
  CustomFileFormat f1;   
  f1.open( "c:/file1.xyz" );
  f1.process();

  CustomFileFormat f2;   
  f2.open( "c:/file2.xyz" );
  f2.process();

  Result r = f1.compare( f2 );
  r.generateReport();

  return 0;
}

The problem that I'm having is with the process() function. This function sends a command to the 3rd party library that exposes a callback function defined like this:

typedef void (*FileProgressCallback)( double dProgress, bool& shouldAbort );

This callback function will be called from the 3rd party library telling me how much of the file has been processed (the received dProgress value will be between 0 and 1) and the shouldAbort bool variable I can use to cause the processing to stop.

The problem that I'm having is I don't know how to code the process() function so that when the callback is called, I know whether the results coming back are for instance f1 or instance f2. Is it possible to define a member function of my CustomFileFormat class, so that when it is called, I know which (this) is being used?

A simple method would be to have a global you set with some context before the .process() call. If you make the global a stack you can even perform recursive processing (although as described it does not sound like that is part of what you need).

A more complex answer would be to use something like libffi's closures (the library is available from https://sourceware.org/libffi/ or https://github.com/libffi/libffi ). That part of the library actually generates (small) bits of code at run-time that can associate additional parameters with those received from a caller.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM