1

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.

Community
  • 1
  • 1
Andrea993
  • 663
  • 1
  • 10
  • 23
  • 3
    You need to include an actual question in your post. As it stands now we have no idea what you need and/or want. – Captain Obvlious Jul 20 '14 at 19:12
  • "Can I call a C++ method from this C callback?" -- What happened when you tried it? "If yes how can I do?" -- What, you don't know how to call a function? – Jim Balter Jul 20 '14 at 19:19
  • I can't call "callme()" function becasue the extern code is out of the class, if I try to call callme() I get an error. – Andrea993 Jul 20 '14 at 19:26
  • So why not get an instance of your C++ class and call `callme` from that object? Your comments in the source allude to the use of an _object_, yet you don't refer to one. – Ryan J Jul 20 '14 at 19:28
  • You can use a [singleton](http://en.wikipedia.org/wiki/Singleton_pattern), but this means there can only be one instance of `myclass` that gets callbacks. – Khouri Giordano Jul 20 '14 at 19:46

1 Answers1

4

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);
}
avakar
  • 32,009
  • 9
  • 68
  • 103