ROS Resources: Documentation | Support | Discussion Forum | Index | Service Status | ros @ Robotics Stack Exchange
Ask Your Question
1

Syntax for extracting string array from srv response in C++

asked 2015-04-01 16:41:19 -0600

Jordan9 gravatar image

I'm trying to call a service and get a response from my ROS package. The specific srv is gazebo_msgs/GetWorldProperties, which is as follows:

---
float64 sim_time
string[] model_names
bool rendering_enabled
bool success
string status_message

I can receive the response, but I cannot figure out how to extract the string array ("model_names") from it in C++. Could anyone give a snippet example of code that would allow me to loop through this string array? The current code (which I just took a wild guess at, but obviously doesn't work) is as follows:

#include "ros/ros.h"
#include <gazebo_msgs/GetWorldProperties.h>

int main(int argc, char **argv)
{
    ros::init(argc, argv, "simWrapper");
    ros::NodeHandle n;
    ros::ServiceClient client = n.serviceClient<gazebo_msgs::GetWorldProperties>("gazebo/get_world_properties");
    gazebo_msgs::GetWorldProperties worldPropSrv;
    if (client.call(worldPropSrv))
    {
        std::vector<String> models = worldPropSrv.response.model_names;
        ROS_INFO("Number of models: %i", models.size());
    }
    else
    {
        ROS_ERROR("Failed to call service get_world_properties");
        return 1;
    }
    return 0;
}

Thanks!

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
3

answered 2015-04-02 02:04:26 -0600

gvdhoorn gravatar image

ROS' built-in string msg type is mapped onto std::string in C++, while ROS msg arrays are mapped onto std::vector<T> (from wiki/msg - 2.1.1 Field Types). Changing std::vector<String> to std::vector<std::string> should work (but in this case the copy is unnecessary, you could just work directly with the message).

edit flag offensive delete link more

Comments

1

Thank you, that makes way more sense now!

Jordan9 gravatar image Jordan9  ( 2015-04-03 10:53:09 -0600 )edit

I'm with Jordan9 on this one: I'm pretty new to C++ and to me that typing is _not_ obvious from wiki/msg - 2.1.1 Field Types.

Will Chamberlain gravatar image Will Chamberlain  ( 2016-02-01 01:06:47 -0600 )edit

While I can sympathise, the information given in the wiki should be more than sufficient when starting with ROS, but already knowing some C++. The Array handling section clearly states that arrays are mapped onto std::vector, with string mapped onto std::string. The rest is normal C++.

gvdhoorn gravatar image gvdhoorn  ( 2016-02-01 02:07:32 -0600 )edit

Question Tools

1 follower

Stats

Asked: 2015-04-01 16:40:21 -0600

Seen: 2,419 times

Last updated: Apr 03 '15