Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use a std::function as a C style callback

How can I use a std::function in a function which expects a C-style callback?

If this is not possible, what is the next best thing?

Example:

// --- some C code I can not change ---
typedef void(*fun)(int);
void register_callback(fun f) {
    f(42); // a test
}
// ------------------------------------

#include <functional>
#include <iostream>

void foo(const char* ptr, int v, float x) {
    std::cout << ptr << " " << v << " " << x << std::endl;
}

int main() {
    std::function<void(int)> myf = std::bind(&foo, "test", std::placeholders::_1, 3.f);
    register_callback(myf); // <-- How to do this?
}
like image 983
Danvil Avatar asked Nov 29 '13 17:11

Danvil


People also ask

How does callback function work in C?

A callback is any executable code that is passed as an argument to other code, which is expected to call back (execute) the argument at a given time [Source : Wiki]. In simple language, If a reference of a function is passed to another function as an argument to call it, then it will be called as a Callback function.

What is callback function and how it works?

A callback function is a function that is passed as an argument to another function, to be “called back” at a later time. A function that accepts other functions as arguments is called a higher-order function, which contains the logic for when the callback function gets executed.

How many types of callbacks are there?

There are two types of callbacks, differing in how they control data flow at runtime: blocking callbacks (also known as synchronous callbacks or just callbacks) and deferred callbacks (also known as asynchronous callbacks).


1 Answers

In most cases you can't.

But when you store a C style callback in your std::function, you can use the target() member function.

like image 139
Drax Avatar answered Oct 08 '22 14:10

Drax