如何将C ++成员函数传递给C API作为参数 [英] How can I pass a C++ member function to a C API as a parameter

查看:97
本文介绍了如何将C ++成员函数传递给C API作为参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的C ++程序中,我需要调用此c API:

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

其中GConnFunc定义为:

  void(* GConnFunc)(GConn * conn) 

我的问题是如果我有一个C ++类,并且有一个成员函数:

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

A :: A code>构造函数,如何将 this-> myfunc 传递给 gnet_conn_new 谢谢。

解决方案

div>

大多数API提供了一个指针大小的用户数据参数,其格式如下:

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

这将允许您传递user_data中的一个实例,并将您的C函数转发给成员函数,如这个:

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

也许你的API在某处有一个替代或类似的user data参数。否则,你不能真正做到没有全局或静态。


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.

这篇关于如何将C ++成员函数传递给C API作为参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆