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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With