使用C ++类的成员函数作为一个C回调函数 [英] Using a C++ class member function as a C callback function

查看:729
本文介绍了使用C ++类的成员函数作为一个C回调函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个C库,需要一个回调函数来注册自定义一些处理。回调函数的类型是 int类型的(INT *,为int *)

我写C ++ $ C $类​​似以下内容并尝试注册一个C ++类的函数作为回调函数C:

  A级{
  上市:
   一个();
   〜A();
   INT E(INT * K,为int * j)条;
};A :: A()
{
   register_with_library(五)
}INT
A :: E(INT * K,为int * E)
{
  返回0;
}A ::〜A()
{}

编译器会引发以下错误:

 在构造函数中'A :: A()',
错误:
 类型的参数'INT(A ::)为(int *,诠释*)'不匹配'INT(*)为(int *,诠释*)。

我的问题:


  1. ,首先是可以注册一个C ++类memeber功能就像我试图做的,如果又如何?
    (我在<读32.8 href=\"http://www.parashift.com/c%2B%2B-faq-lite/mixing-c-and-cpp.html\">http://www.parashift.com/c++-faq-lite/mixing-c-and-cpp.html.但在我看来,这并没有解决问题)

  2. 是否有替代/更好的办法来解决呢?


解决方案

您可以做,如果成员函数是静态的。

A类的非静态成员函数的类型为类A * 对应的这个的指针的一个隐含的第一个参数。这就是为什么你可以只登记他们,如果回调的签名也有过的第一个参数类A * 键入

I have a C library that needs a callback function to be registered to customize some processing. Type of the callback function is int a(int *, int *).

I am writing C++ code similar to the following and try to register a C++ class function as the callback function:

class A {
  public:
   A();
   ~A();
   int e(int *k, int *j);
};

A::A()
{
   register_with_library(e)
}

int
A::e(int *k, int *e)
{
  return 0;
}

A::~A() 
{

}

The compiler throws following error:

In constructor 'A::A()',
error:
 argument of type ‘int (A::)(int*, int*)’ does not match ‘int (*)(int*, int*)’.

My questions:

  1. First of all is it possible to register a C++ class memeber function like I am trying to do and if so how? (I read 32.8 at http://www.parashift.com/c++-faq-lite/mixing-c-and-cpp.html. But in my opinion it does not solve the problem)
  2. Is there a alternate/better way to tackle this?

解决方案

You can do that if the member function is static.

Non-static member functions of class A have an implicit first parameter of type class A* which corresponds to this pointer. That's why you could only register them if the signature of the callback also had the first parameter of class A* type.

这篇关于使用C ++类的成员函数作为一个C回调函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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