实际中常常需要通过对其他节点消息的内容进行处理后再发布消息,这就往往希望能够在回调函数中进行处理函数的书写和消息的发布 。最初网上说采取全局变量直接在回调函数书写发布函数,但是不知道为什么代码是不报错,但是内容发布不出来。后面在论坛中发现可以定义一个类来实现这一功能,具体过程如下:
#include "ros/ros.h"
#include "std_msgs/Float32.h"
#include "test1/msg1.h"
#include <iostream>
using namespace std;
class SubscribeAndPublish
{
public:
SubscribeAndPublish()
{
//Topic you want to publish
pub_ = n_.advertise<msg_type>("/published_topic", 1);
//Topic you want to subscribe
sub_ = n_.subscribe("/subscribe_topic", 1, &SubscribeAndPublish::callback, this);
}void callback(const msg_type::ConstPtr& msg)
{
//PUBLISHED_MESSAGE_TYPE output;
//.... do something with the input and generate the output...
msg_type output;
ou