vendredi 5 janvier 2018

Converting a lambda to function pointer typedef

I have a 3rd party API that has a function that takes a function pointer as an argument (sample types):

// defined in "Api.h"
typedef int (*Callback) (int x); 

unsigned char ApiCall(int p, Callback cb);


int ApiCall(int p, Callback cb) {
   return cb(p);
}

And I'm trying interact with this API using a class instance method; here's a sample class:

class ApiWrapper {
    public:
        int ApiCallback(int x) { return this->factor_ * x; }

        static int WorkingApiCallback(int x) { return 3 * x; }

        ApiWrapper(int f) { this->factor_ = f; }

    private:
        int factor_;
} 

And a main function to test:

#include <iostream>
#include <functional>

int main() {
    ApiWrapper a(2);

    using std::placeholders::_1;
    std::function<int(int)> lambda = std::bind( &ApiWrapper::ApiCallback, a, _1 );

    std::cout << "Class: "  << a.ApiCallback(21) << std::endl;
    std::cout << "Lambda: " << lambda(21) << std::endl;
    std::cout << "Static ApiCall:" << ApiCall(21, ApiWrapper::WorkingApiCallback) << std::endl;

    // NOT WORKING 
    std::cout << "Static ApiCall:" << ApiCall(21, lambda) << std::endl;
    std::cout << "Static ApiCall:" << ApiCall(21, this.ApiCallback) << std::endl;    

    return 0;
}

Is there a way to achieve this without using the static member; as I need to associate/use state each time the callback is invoked by the 3rd party lib.

Thanks!

Aucun commentaire:

Enregistrer un commentaire