gio-dbus-client.cpp 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. #define GI_INLINE 1
  2. #include <gio/gio.hpp>
  3. #include <iostream>
  4. namespace GObject_ = gi::repository::GObject;
  5. namespace GLib = gi::repository::GLib;
  6. namespace Gio = gi::repository::Gio;
  7. static GLib::MainLoop loop;
  8. // many calls here support GError
  9. // so typically will throw here instead
  10. // (unless GError output is explicitly requested in call signature)
  11. // NOTE abundancy of gi::expect not generally needed;
  12. // only needed when using --dl and --expected
  13. static void
  14. on_reply(GObject_::Object ob, Gio::AsyncResult result)
  15. {
  16. // if not caught here, it will be caught before returning to plain C
  17. try {
  18. auto connection = gi::object_cast<Gio::DBusConnection>(ob);
  19. auto call_result = gi::expect(connection.call_finish(result));
  20. // get single array child
  21. auto names = gi::expect(call_result.get_child_value(0));
  22. int count = gi::expect(names.n_children());
  23. std::cout << count << " message bus names: " << std::endl;
  24. for (int i = 0; i < count; ++i)
  25. std::cout << gi::expect(
  26. gi::expect(names.get_child_value(i)).get_string(nullptr))
  27. << std::endl;
  28. } catch (const GLib::Error &error) {
  29. std::cerr << "error: '" << error.what() << "'." << std::endl;
  30. }
  31. // quit when idle
  32. GLib::idle_add([]() {
  33. loop.quit();
  34. return GLib::SOURCE_REMOVE_;
  35. });
  36. }
  37. int
  38. main(int argc, char ** /*argv*/)
  39. {
  40. auto bustype = argc <= 1 ? Gio::BusType::SESSION_ : Gio::BusType::SYSTEM_;
  41. auto connection = gi::expect(Gio::bus_get_sync(bustype));
  42. connection.call("org.freedesktop.DBus", "/org/freedesktop/DBus",
  43. "org.freedesktop.DBus", "ListNames", nullptr, nullptr,
  44. Gio::DBusCallFlags::NONE_, -1, nullptr, on_reply);
  45. loop = gi::expect(GLib::MainLoop::new_());
  46. loop.run();
  47. }