Ask Your Question
0

Can I define publishers in a function and then I can call that function in main() file? Can I really?

asked 2013-08-29 01:40:05 -0500

this post is marked as community wiki

This post is a wiki. Anyone with karma >75 is welcome to improve it.

I just wanted to ask whether I can define my publisher in a function and then call the function in a main() file like the following code sniplet exhibits:

static void myfunct(stream* str, strble *conv, unsigned char *buff, int n){
ros::NodeHandle nh;
ros::Publisher pub_navigation_msg = nh.advertise<rtklib::Navigation>("nav_topic", 10);

rtklib::Navigation navmsg;
navmsg.time= conv->time;

pub_navigation_msg.publish(navmsg);
}


int main(int argc, char** argv){

    ros::Rate r(1); 
    while (ros::ok()){
      myfunct();
    }   
ros::spinOnce();
}
edit retag flag offensive close merge delete

1 Answer

Sort by » oldest newest most voted
1

answered 2013-08-29 01:56:23 -0500

dornhege gravatar image

Yes, you can, in principle. However, your code won't work.

I'm not sure which of several problems you want us to ignore, but to at least address the major concerns regarding publishers: You need to create a publisher just once, but once it is created you need to make sure that the publisher stays somewhere and isn't destroyed.

edit flag offensive delete link more

Comments

I have edited the above code. Do you think it will work like this. Because I also defined by Nodehandler inside the function. I thought we can only define nodehandler and publisher inside a main file.

Gudjohnson gravatar image Gudjohnson  ( 2013-08-29 02:02:58 -0500 )edit

The problem is that you are always recreating a new publisher and the old one gets destroyed before you leave the function. When you publish to you newly created one it will very likely not have build up a connection yet.

dornhege gravatar image dornhege  ( 2013-08-29 02:39:38 -0500 )edit

It is no problem to create a publisher in a function, just do it once before your main loop, make sure that it doesn't get destroyed and not re-create a new one over and over in a loop.

dornhege gravatar image dornhege  ( 2013-08-29 02:39:43 -0500 )edit

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account.

Add Answer

Question Tools

1 follower

Stats

Asked: 2013-08-29 01:40:05 -0500

Seen: 136 times

Last updated: Aug 29 '13