Andrea993
Andrea993

Reputation: 693

call a C++ method from a C callback

I'm using a C library into a C++ project. This library allow me to register a C callback and in this callback I should call a C++ method of an object.

The situation is this:

myclass.h

class myclass
{
public:
    myclass();
    void callme();
};


extern "C"
{
     void init():
     int callback(int,int);
}

myclass.cpp

myclass::myclass()
{
   init();
}

void myclass::callme()
{
   cout<<"Ok\n";
}

    extern "C"
    {
       void init()
       {
          //code 

          setlibraryCallback(callback);

          //code
       }


       int callback(/*some arguments that I can't change*/ int a, int b)
       {
          //I should call  "callme()" methos of my c++ object
       }
    }

Can I call a C++ method from this C callback? If yes how can I do? Thanks

EDIT: I found this similar question How to call a C++ method from C? However I cant pass the object as void pointer to the C callback because I can't change the callback arguments.

Upvotes: 1

Views: 1638

Answers (1)

avakar
avakar

Reputation: 32635

A library will usually allow you to provide a void * value as a "context", which is then passed to the callback. If the library doesn't provide that functionality (huh?), you can use a thread-local variable (also known as a global variable in single-threaded programs) instead.

This is how the code will often look like.

class A {
public:
    static void static_callback(void * ctx) {
        static_cast<A*>(ctx)->callback();
    }
    void callback();
};

extern void library_function(void (*callback)(void *), void * ctx);

int main()
{
    A a;
    library_function(&A::static_callback, &a);
}

Upvotes: 4

Related Questions