The method to use is get_topic_names_and_types
.
That is what ros2 topic list
uses, as well as for instance what the RQT topic plugin uses to list the available topics. These are both in Python, but the method is the same in C++.
However, do take into account this comment: https://github.com/ros2/ros2/issues/1...
In general, it can take some time for discovery to happen. That's because we are currently doing "P2P" discovery on the backend, and if you create a Node and call get_topic_names_and_types on it right away, discovery may not have happened yet. It may make sense to add a timeout to get_topic_names_and_types; I'm not sure.
The command-line tools get around this a different way. When you launch any ros2 command-line tool the first time, a daemon is spun up in the background. The daemon then does discovery, and hangs around. The command-line tool then queries the daemon for information. You may want to think about architecting something more like that; currently rapidly creating Nodes doesn't always do the discovery you want (as you discovered)
So if you use the method right at startup you may not get the full results. That may also be what happened for you with get_node_names
.