problem
I have the following C callback signature from a C library called Foo:
void (* RequestCallbackFunc)(int)
This library also provides a utility function for registering said callback.
extern void SetRequestCallback(RequestallbackFunc request_cbf);
I have a C++ class App with a instance method HandleRequest. What’s the correct way to have HandleRequest called when request_cbf is called?
my naive solution
App.hpp
#include <Foo.h> // include my C library
#include <Bar.hpp>
class App {
public:
App();
~App();
void HandleRequest(int x);
public:
Bar * bar_; // raw pointer for demonstration purposes
}
App.cpp
#include "App.hpp"
extern "C" {
static void handle_request(int x);
}
static void handle_request(int x) {
static std::auto_ptr<App> my_app( new App() );
my_app->HandleRequest(x);
}
App::App() {
SetRequestCallback( handle_request );
bar_ = new Bar();
}
App::~App() {
delete bar_;
}
void App::HandleRequest(int x) {
bar_->DoSomething( x );
// more 'work'...
}
Am I approaching this problem the correct way? Are there additional ways to interface C++ with C callbacks?
why use pointers?
(Same goes for
Bar), though to be honest, you may as well call the method inBardirectly (unless the redirection throughAis required)Alternatively, rather than a free function, pass in a pointer to a static function in
Amatching the same signature – inside this you can access the single instance ofAto use…btw. some apis use a pattern where during registration you can pass in a pointer to some user data, which is passed in the callback, this could be for example a pointer to an instance of
Ato handle the callback – this way you can avoid all the singleton business…