当前位置: 代码迷 >> 综合 >> 回调函数机制
  详细解决方案

回调函数机制

热度:11   发布时间:2024-01-24 22:08:17.0

 首先创建一个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;
}

然后对应的头文件

#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){d_ptr_=std::make_shared<d_ptr>(app_i);//传入参数//括号的参数传递要一致d_ptr_->setDPtrCallback(std::bind(&d_ptr_app::DPtrHander, this, std::placeholders::_1));//是在src定义的,里面的函数是在app中定义的}private:void DPtrHander(int i_){std::cout<<"hello call back"<<std::endl;//这边是回调函数输出的东西}std::shared_ptr<d_ptr>  d_ptr_;//定义一个相关的指针int app_i=999;//   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=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){d_ptr_callback_ = handler;};void SubFromAPP(){while(true){if (d_ptr_callback_){d_ptr_callback_(data_);}        std::cout<<"我在sub的线程里面了"<<std::endl;}  };
private://std::shared_ptr<>  davidhan_ptr;d_ptr_callback d_ptr_callback_;std::thread sub_thread_;uint32_t data_;int data_app;
};

 

 

 

  相关解决方案