How would you publish a message in ROS of a vector of structs?

天大地大妈咪最大 提交于 2019-12-04 05:22:47
Avio

Just to expand a little bit what @Sterling already explained...

If you have a project (and thus directory) called "test_messages", and you have these two types of message in test_messages/msg:

#> cat test.msg 
string first_name
string last_name
uint8  age
uint32 score

#> cat test_vector.msg 
string vector_name
uint32 vector_len         # not really necessary, just for testing
test[] vector_test

You can then write this C++ code:

#include "test_messages/test.h"
#include "test_messages/test_vector.h"

...

  ::test_messages::test test_msg;

  test_msg.age          = 29;
  test_msg.first_name   = "Firstname";
  test_msg.last_name    = "Lastname";
  test_msg.score        = 79;

  test_pub.publish(test_msg);


  ::test_messages::test_vector test_vec;

  test_vec.vector_len    = 5;
  test_vec.vector_name   = std::string("test vector name");

  for (int idx = 0; idx < test_vec.vector_len; idx++)
  {
      test_msg.age          = 50;
      test_msg.score        = 100;
      test_msg.first_name   = std::string("aaaa");
      test_msg.last_name    = std::string("bbbb");

      test_vec.vector_test.push_back(test_msg);
  }

  test_vector_pub.publish(test_vec);

Let's say your first msg is called MyStruct. To have a msg that is an array of MyStructs, you would have a .msg with the field:

MyStruct[] array

Then in the code you make a MyStruct and set all the values:

MyStruct temp;
temp.upperLeft = 3
temp.lowerRight = 4
temp.color = some_color
temp.cameraID = some_id

Then to add MyStructs to an array your array in the second .msg type, you can use push_back (just like with std::vector):

MySecondMsg m;
m.push_back(temp);
my_publisher.publish(m);
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!