mercredi 6 septembre 2017

C++ Callbacks -- std::function vs Function Pointer

Having an interesting problem and looking for some clarification. I have working example using old function pointer method, but was attempting to use a std::function wrapper, but now it no longer works.

The example code was to start implementing a callback mechanism, when I use the function pointer approach I obtain the desired results.

callback initiated, m_callback = 0
callback initiated, m_callback = 1
callback initiated, m_callback = 0
callback initiated, m_callback = 1
...

But when using the std::function wrapper approach I do not get the intended results.

callback initiated, m_callback = 0
callback initiated, m_callback = 0
callback initiated, m_callback = 0
callback initiated, m_callback = 0
...

Anyone able to point out any errors that I've made? I comment/uncomment between the two approaches (function pointers vs function wrapper).

#include <iostream>
#include <functional>
#include <chrono>
#include <thread>

void callback(int callback)
{
    int m_callback = callback;
    std::cout << "m_callback = " << m_callback << std::endl;
}

void foo(void (*ptr)(int))
// void foo(std::function<void(int)> ptr)
{
    std::this_thread::sleep_for(std::chrono::milliseconds(500));
    int callback = (callback == 0) ? 1 : 0;
    ptr(callback);
}

// ----------------------------------------------------------------

int main(int argc, char ** agrv)
{
    void (*func_ptr)(int) = &callback;
    std::function<void(int)> std_func_ptr = &callback;

    while(1)
    {
        foo(func_ptr);
        // foo(std_func_ptr);
    }

    return 0;
}

Aucun commentaire:

Enregistrer un commentaire