I want to access listener::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.
I changed the access modifiers of the flow_message
to private and protected but it gets the compilation error and I found that the only way to access this variable in the main function, is to define it as public. I can get some properties like the size of the flow_message
vector, in the main using the below command:
list.flow_message.size();
but for example, when I want to access the first member of the flow_message
vector, using the below command I get the segmentation fault error.
list.flow_message[0];
// this is my code for subscribing the optical flow data
// using a class for subscriber callback function:
#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;
}
as I mentioned before my error is in run time:
Segmentation fault (core dumped)
thanks for any help or comment...
You go fetch flow_message[0]
but you never add elements into the vector. If the vector is empty, then flow_message[0]
don't exist.
Too add elements in the vector, you should publish a message.
But you also should check for elements in the vector:
while(ros::ok()) {
if (list.flow_message.empty()) {
std::cout << "no messages" << std::endl;
} else {
std::cout << "this is it: " << list.flow_message[0] << std::endl;
}
ros::spinOnce();
}