Ask Your Question
0

How to access a public variable of subscriber class in the main function?

asked 2019-08-29 09:41:47 -0500

Hi there. I want to access "flow_message" (a public variable) which I defined in the subscriber class, in the main() function of my code. in the below code I just did a simple printing of the "flow_message" parameter to show the problem. the compilation has no error but when I run the subscriber node I get this error:

"Segmentation fault (core dumped)"

and this is the code:


#include<ros/ros.h>
#include<opencv_apps/FlowArrayStamped.h>
#include<opencv_apps/FlowArray.h>
#include<opencv_apps/Flow.h>
#include<opencv_apps/Point2D.h>
#include<vector>
#include<numeric>

using namespace std;

class listener
{
public:
    vector<opencv_apps::Flow> flow_message;
    void callback(const opencv_apps::FlowArrayStamped::ConstPtr& msg);

};

void listener::callback(const opencv_apps::FlowArrayStamped::ConstPtr& msg)
{
    listener::flow_message = msg->flow;
    ROS_INFO("i got it");
}

int main(int argc, char **argv)
{
    ros::init(argc, argv, "dataman");
    ros::NodeHandle n;
    listener list;
    ros::Subscriber sub = n.subscribe("/lk_flow/flows", 1, &listener::callback, &list);
    while(ros::ok())
    {
    cout << "this is it: " << list.flow_message[0] << endl;
    ros::spinOnce();
    }
   return 0;
}

maybe my question would be so simple, but I searched and worker too much on it but I could not solve it. so thanks for any help...

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
1

answered 2019-08-29 10:29:32 -0500

mjcarroll gravatar image

It's likely that you are trying to print the contents of the list.flow_message[0] before any data has been inserted into the vector. You should verify that the list.flow_message has contents before attempting to print.

You could use std::vector::empty or std::vector::size

edit flag offensive delete link more

Comments

Hi Carroll. you are right. I checked it using the empty() function. I found that when I run the node, first it outputs 1, and after a while, it outputs 0. so at start of running the node the variable is empty. so the problem solved by adding and if-else part to check if the data is empty print some messages:

if(list.flow_message.empty())
  {
  cout << "the message is empty" << endl;
 }
else 
  {
      cout << " the message is : " << list.flow_messge[0] << endl;
   }

so thanks a lot for your fast answer!!!!!!!!!!!

Amir Reza Sadeghi gravatar imageAmir Reza Sadeghi ( 2019-08-29 10:47:08 -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: 2019-08-29 09:41:47 -0500

Seen: 14 times

Last updated: Aug 29