函数指针使用c++类成员函数

使用一些C的库时,需要让类的成员函数对接C的回调函数指针。
以pthread为例,利用类里的一个静态函数作为pthread_create的参数,将类的this指针传给这个静态函数,然后就可以想干什么干什么了。

点击(此处)折叠或打开

  1. template <typename A, typename R>
  2. class thr: public boost::noncopyable
  3. {
  4. private:
  5.     typedef A arg_t;
  6.     typedef R res_t;
  7.     typedef pthread_t tid_t;
  8.     typedef boost::function func_t;
  9.     thr(){}
  10.     tid_t _tid;
  11.     arg_t _arg;
  12.     res_t _res;
  13.     func_t _func;

  14.     static void* _thread_func(void* arg)
  15.     {
  16.         ((thr*)arg)->func();
  17.         return NULL;
  18.     }
  19. public:
  20.     explicit thr(func_t func, arg_t arg): _func(func), _arg(arg){}
  21.     ~thr(){}
  22.     tid_t get_tid() {return _tid;}
  23.     arg_t get_arg() {return _arg;}
  24.     res_t get_result() {return _res;}
  25.     void set_arg(arg_t arg) {_arg = arg;}
  26.     void set_result(res_t res){_res = res;}

  27.     void func() {_res = _func(_arg);}
  28.     int run() {return pthread_create(&_tid, NULL, _thread_func, this);}
  29.     int join()
  30.     {
  31.         void* p;
  32.         return pthread_join(_tid, &p);
  33.     }
  34. };

  35. class test
  36. {
  37. public:
  38.     char* f(int i)
  39.     {
  40.         char* s = new char[10];
  41.         sprintf(s, "%d", i);
  42.         return s;
  43.     }
  44. };

  45. int main()
  46. {
  47.     test te;
  48.     thr th(boost::bind(&test::f, te, _1), 123);
  49.     th.run();
  50.     th.join();

  51.     char* s = th.get_result();
  52.     cout << th.get_result() << endl;
  53.     delete[] s;
  54.     return 0;
  55. }



上面为了方便用了boost::function。使得整个类和boost::thread功能有点重复。
如果不想用boost,可以想下面这样,用继承的方式。
class thr
{
protected:
    pthread_t _tid;

    static void* _thread_func(void* arg) {return ((thr*)arg)->_func();}
    virtual void* _func() = 0;
    thr(const thr& o){}
public:
    thr(){}
    ~thr(){}
    int start_thread()
    {
        int re = pthread_create(&_tid, NULL, _thread_func, this);
        if(re != 0) return re;
    }

    int join_thread()
    {
        void* p;
        if(pthread_join(_tid, &p) != 0) return -1;
        cout << (*(int*)p) << endl;
        return 0;
    }
};

class test : public thr
{
private:
    int _i;
    void* _func()
    {
        cout << "thread begin" << endl;
        return &_i;
    }
public:
    test(int i):_i(i){}
};

int main()
{
    test te(10);
    te.start_thread();
    te.join_thread();
    return 0;
}







来自 “ ITPUB博客 ” ,链接:http://blog.itpub.net/26239116/viewspace-2123701/,如需转载,请注明出处,否则将追究法律责任。

转载于:http://blog.itpub.net/26239116/viewspace-2123701/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值