Search code examples
c++ros

ROS - get current available topic in code (not command)


I want to get current available topics in my code so that I can set up publisher and subscribber accordingly. I know command 'rostopic list' would show this, but I want to get the information when my program is running.

Is there any API could do this?


Solution

  • Post edited after Gabor Meszaros's answer.

    You find ROS C++ API reference (roscpp) here and - as in Python - you'll find getTopics method in ros::master subsection.

    Here is a sample code of how to use it:

    ros::master::V_TopicInfo master_topics;
    ros::master::getTopics(master_topics);
    
    for (ros::master::V_TopicInfo::iterator it = master_topics.begin() ; it != master_topics.end(); it++) {
      const ros::master::TopicInfo& info = *it;
      std::cout << "topic_" << it - master_topics.begin() << ": " << info.name << std::endl;
    }