C++ Callback Using Class Member

Using a C++ class member function as a C callback function

You can do that if the member function is static.

Non-static member functions of class A have an implicit first parameter of type class A* which corresponds to this pointer. That's why you could only register them if the signature of the callback also had the first parameter of class A* type.

C++ callback using class member

Instead of having static methods and passing around a pointer to the class instance, you could use functionality in the new C++11 standard: std::function and std::bind:

#include <functional>
class EventHandler
{
public:
void addHandler(std::function<void(int)> callback)
{
cout << "Handler added..." << endl;
// Let's pretend an event just occured
callback(1);
}
};

The addHandler method now accepts a std::function argument, and this "function object" have no return value and takes an integer as argument.

To bind it to a specific function, you use std::bind:

class MyClass
{
public:
MyClass();

// Note: No longer marked `static`, and only takes the actual argument
void Callback(int x);
private:
int private_x;
};

MyClass::MyClass()
{
using namespace std::placeholders; // for `_1`

private_x = 5;
handler->addHandler(std::bind(&MyClass::Callback, this, _1));
}

void MyClass::Callback(int x)
{
// No longer needs an explicit `instance` argument,
// as `this` is set up properly
cout << x + private_x << endl;
}

You need to use std::bind when adding the handler, as you explicitly needs to specify the otherwise implicit this pointer as an argument. If you have a free-standing function, you don't have to use std::bind:

void freeStandingCallback(int x)
{
// ...
}

int main()
{
// ...
handler->addHandler(freeStandingCallback);
}

Having the event handler use std::function objects, also makes it possible to use the new C++11 lambda functions:

handler->addHandler([](int x) { std::cout << "x is " << x << '\n'; });

How to make a callback in C++: use a class member function as a parameter

Here is a working way to do that:

void myOtherFunction(std::function<void()> oneOfMyFunctions) {
oneOfMyFunctions();
}

And inside my class:

myOtherFunction([&] {
oneOfMyFunctions();
});

Some explanations:
In std::function<void()>, void is what is returned by the function and () contains the types of its parameters (mine is empty because it doesn't have any).

In the 2nd code I am using a lambda to keep the context, as a bind would do (but lambdas replace them).

Map C++ member function to C callback

Use the user_data pointer to give you back a pointer to the class that owns the callback. For example.

void MyCallback(char port, uint8_t interrupt_mask, uint8_t value_mask, void *user_data)
{
static_cast<Example *>(user_data)->Callback(port, interrupt_mask, value_mask);
}

class Example
{
public:

Example()
{
//setup callback here - i dont know what library you're using but you should be able to pass a this pointer as user_data
init_lib(fictionalparameter1, fictionalparameter2, this);
}

private:

void Callback(char port, uint8_t interrupt_mask, uint8_t value_mask)
{
//callback handler here...
}

friend void MyCallback(char port, uint8_t interrupt_mask, uint8_t value_mask, void *user_data);
};

Calling C++ class methods from C using callbacks

The classical C way of passing callbacks is to pass two values: a pointer to the callback itself, and an opaque pointer which will be passed to the callback as an additional argument (take a look at qsort_r for example). When interfacing with C++, that opaque value may be used as instance pointer; you will only need to write a thin wrapper:

class B {
void my_callback(int arg);
static void my_callback_wrapper(int arg, void *u) {
((B*)u)->my_callback(arg);
}
};

// or even:
extern "C" void my_callback_wrapper(int arg, void *u) {
((B*)u)->my_callback(arg);
}

and pass a pointer to the wrapper, along with a pointer to the object, to the C part. Be careful to use the exact same class type on both sides and not base/derived classes, for example.

Note that while it may be possible to get a pointer to the (non-static) method itself, on some compilers (tested on MSVC a long time ago) they have a special calling convention so that the pointer will not be compatible with any normal function pointer.

How to modify C++ class member variables from C callback

If the C callback is yours or you can change it, you may pass a pointer to the class instance and call some member function in the static method:

extern "C" 
{
void SomeCFunctionThatRequireCallback(void * ptr, void (*FuncPtr)(void *, int, int))
{
FuncPtr(ptr, 80, 20);
}
}

TTerm()
{
SomeCFunctionThatRequireCallback(this, OnResizeCallback);
}

static void OnResizeCallback(void * ptr, int Width, int Height)
{
// Set this->Width and this->Height
TTerm * instance = (TTerm*)ptr;
instance->Width = Width;
instance->Heght = Height;
}

You could pass the ints as references also. But, again, you need to modify the callback signature.

If you can't change the callback signature, you have to keep control of who calls the callback and do something in the static method.

You could protect the callback with a semaphore in another class and get the needed data from there.

(Non compiling example.)

TTerm() {
SomeCFunctionObject & obj = SomeCFunctionObject.getInstance();
obj.setCaller (this);
obj.doCallback ();
Width = obj._width;
Height = obj._height;
}

class SomeCFunctionObject {
public:
int _width;
int _height;

static SomeCFunctionObject & getInstance () {
static SomeCFunctionObject obj;
return obj;
}

static void OnResizeCallback(int Width, int Height)
{
SomeCFunctionObject & obj = SomeCFunctionObject.getInstance();
obj._width = Width;
obj._height = Height;
// free semaphore
}
void setCaller (void * using) {
// get semaphore
_using = using
}

void doCallback () {
SomeCFunctionThatRequireCallback(OnResizeCallback);
}

private:
void * _using;

SomeCFunctionObject () {}

};

How can I pass a class member function as a callback?

That doesn't work because a member function pointer cannot be handled like a normal function pointer, because it expects a "this" object argument.

Instead you can pass a static member function as follows, which are like normal non-member functions in this regard:

m_cRedundencyManager->Init(&CLoggersInfra::Callback, this);

The function can be defined as follows

static void Callback(int other_arg, void * this_pointer) {
CLoggersInfra * self = static_cast<CLoggersInfra*>(this_pointer);
self->RedundencyManagerCallBack(other_arg);
}

C++ Member function as a callback

There are two problems:

  • std::mem_fn(&app::callback) takes an instance of app as the first parameter.
  • The most idiomatic alternative would be to use a capturing lambda such as
    [this] (Json::Value& json) { return callback(json); }
    but these cannot be converted to function pointers, which makes implementing generic containers for storing and dynamically dispatching to them extremely difficult to do.

One possible approach is to amend your websocket interface and accept an optional void* context parameter like this:

using cb = int(*)(Json::Value &json, void* ctx);

static void websocket::listen(cb callback, const char* address, void* ctx = nullptr)
{
...
}

int app::callback(Json::Value& json)
{
return db->insert(json);
}

void app::start()
{
websocket::listen([] (Json::Value &json, void* ctx) -> int {
return static_cast<app*>(ctx)->callback(json);
}, path, this);
}

If you prefer more type safety for this erasure, you can consider std::any:

using cb = int(*)(Json::Value &json, std::any ctx);

static void websocket::listen(cb callback, const char* address, std::any ctx = {})
{
...
}

int app::callback(Json::Value& json)
{
return db->insert(json);
}

void app::start()
{
websocket::listen([] (Json::Value &json, const std::any& ctx) -> int {
return std::any_cast<app*>(ctx)->callback(json);
}, path, this);
}

The std::any_cast will throw a std::bad_any_cast if ctx was empty or storing a pointer that wasn't a type erased app*.



Related Topics



Leave a reply



Submit