How can I input a publisher as a parameter to a function?

I am planning on defining the following publisher in a main() file

 ros::Publisher pub_navigation_msg = nh.advertise<rtklib::Navigation>("nav_topic", 10);


But I want to use publisher inside my function so I want to define it as a parameter to the function like

static void myfunct(ros::Publisher pub, stream mymsg){
.....
.....
pub.publish(mymsg);

}


I think I cannot define a publisher outside a main() file because main would consist of Nodehandler and other important ros features.

edit retag close merge delete

how do you do it finally? I want to use in different files

( 2017-08-08 09:47:12 -0500 )edit

Sort by » oldest newest most voted

I'm not sure how publisher react to copying (my guess is it would be safe), but it should be better to just pass it by reference here.

more

I think this statement in your original post is probably false:

I think I cannot define a publisher outside a main() file because main would consist of Nodehandler and other important ros features.

ROS creates one node for each executable process. This is set up by your ros::init() call. You can then create as many NodeHandle as you want. Each NodeHandle points to the same underlying ROS node. It's typical to create a single NodeHandle and re-use it wherever needed, but that's not a requirement. The only requirement is that you must call ros::init() before creating any NodeHandle objects.

So, if needed, you can just create a new NodeHandle inside your function and use that to construct the publisher you need. Note that this may not be the best design, if your function is called frequently. Creating a new NodeHandle is cheap, but creating a new publisher involves advertising a new topic to the ROS master and connecting to any subscriber nodes, which can be "expensive".

If you call the function each time you want to publish a new message, then you should declare the publisher external to the function: - as a global var (use a boost::shared_ptr<ros::publisher> to make sure it gets created after the ros::init() call) - as a class member variable - passed to the function by reference (probably the easiest) - passed to the function by boost::shared_ptr<ros::publisher>

more

You can define publisher as global variable without initializing it. You can later initialize publisher with node handler within main() after ros::init(). In this way you can use publisher outside main within any function.

more