Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I pass a C++ member function to a C API as a parameter

Tags:

c++

In my C++ program, I need to call this c API:

GConn* gnet_conn_new (const gchar *hostname,
                      gint port,
                      GConnFunc func);

where GConnFunc is defined as:

void (*GConnFunc) (GConn *conn);

My question is if I have a C++ class and have a member function like:

Class A {
 public:
   A();
   void my_func (GConn* conn);
}

In my A::A() Constructor, how can I pass this->myfunc to gnet_conn_new as the GConnFunc parameter?

Thank you.

like image 889
michael Avatar asked Mar 25 '10 16:03

michael


1 Answers

Most APIs provide a pointer-sized 'user data' argument, which would look like this:

GConn* gnet_conn_new (const gchar *hostname, 
                  gint port, 
                  GConnFunc func,
                  void* user_data); 

This would allow you to pass an instance in user_data and have your C function forward to the member function like this:

void my_func(GConn *conn, void* user_data)
{
    ((MyClass*)user_data)->MyMemberFunc(conn);
}

Perhaps your API has an alternative or similar 'user data' parameter somewhere. Otherwise, you can't really do it without globals or statics.

like image 123
AshleysBrain Avatar answered Oct 14 '22 04:10

AshleysBrain