回调函数机制

给你一囗甜甜゛ 提交于 2020-01-28 07:26:55

 首先创建一个d_ptr_app.cpp

#include<iostream>
#include<ptr_app.h>
#include<ros/ros.h>
int main(int argc, char** argv)
{
ros::init(argc, argv, "davidhan_Ptr");
ros::NodeHandle nh("~");
d_ptr_app ptr_app_(nh);
ros::spin();
return 0;
}

然后对应的头文件ptr_app.h

#ifndef  PTR_APP_H
#define PTR_APP_H
#include <iostream>
#include <memory>
#include <ptr.h>
#include <ros/ros.h>
#include <std_msgs/UInt32.h>
class d_ptr_app
{
    public:
    d_ptr_app(ros::NodeHandle& nh):app_i(1)
    {
        //nh_=nh;
        d_ptr_=std::make_shared<d_ptr>(app_i);//传入参数
        //括号的参数传递要一致
        d_ptr_->setDPtrCallback(std::bind(
                &d_ptr_app::DPtrHander, this, std::placeholders::_1));//是在src定义的,里面的函数是在app中定义的
       pub_=nh.advertise<std_msgs::UInt32>("/davidhan_data",1,this);
       count_data.data=0;
    }
    private:
    void DPtrHander(int i_)
    {
        std::cout<<"hello call back"<<std::endl;
        count_data.data++;
      pub_.publish(count_data);//在回调的hand里面去publiser topic
     
        //这边是回调函数输出的东西

    }
    std::shared_ptr<d_ptr>  d_ptr_;//定义一个相关的指针
    std::shared_ptr<d_ptr>  pub_d_ptr;//定义一个相关的指针
    int app_i=999;
    ros::Publisher pub_;
//    ros::NodeHandle nh_;
    std_msgs::UInt32  count_data;
} ;
#endif // !   

在ptr.h头文件中

#ifndef PTR_H
#define PTR_H
#include <iostream>
#include <pthread.h>
#include <thread>
#include <functional>
class d_ptr
{
public:
   d_ptr(int app_i):data_(app_i),flag(false)
   {
         data_app=app_i;
         std::cout<<"data_app="<<data_app<<std::endl;
         sub_thread_ = std::thread(&d_ptr::SubFromAPP,this);
         //sub_thread_ = std::thread(&SubFromAPP,this);//没有的话,就会报错
         std::cout<<"在d_ptr实例化线程里面"<<std::endl;
   };
   //std::funciton<返回数值类型(输入类型)>
   typedef std::function<void(uint32_t&)> d_ptr_callback;

   void setDPtrCallback( d_ptr_callback handler)
    {
       std::lock_guard <std::mutex> guard(ptr_mutex);
        d_ptr_callback_ = handler;
       flag=true;
    };
    void SubFromAPP()
      {
      while(true)
      {
           if (d_ptr_callback_)
             {
                  d_ptr_callback_(data_);
                  data_++;
             }   
            if(!flag)
            {
               std::cout<<"not ready"<<std::endl;
                continue;
            }     
         std::cout<<"我在sub的线程里面了"<<std::endl;
      }  
    };
private:
   //std::shared_ptr<>  davidhan_ptr;
   d_ptr_callback d_ptr_callback_;
   std::mutex  ptr_mutex;
   std::thread sub_thread_;
   uint32_t data_;
   int data_app;
   bool flag;
};


#endif

 

 

 

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!