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

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

问题描述

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



并尝试注册一个C ++类函数作为回调函数:

  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()
{

}

编译器会抛出以下错误:

  (int *,int *)'的类型为'int(A ::)(int *,int *)'的参数不匹配'int(*)',
错误:

我的问题:


  1. 首先是可能注册一个C ++类的memeber函数,就像我想做的,如果是这样怎么办?
    (我在 http:/ /www.parashift.com/c++-faq-lite/mixing-c-and-cpp.html ,但在我看来它不能解决问题)


  2. 解决方案

    你可以这样做,如果成员函数是静态的。



    类A的非静态成员函数具有类A * 其对应于指针。这就是为什么你只能注册它们,如果回调的签名也有 class 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天全站免登陆