msg_lookup.cpp
Go to the documentation of this file.
1 
31 #include "Python.h"
32 
33 namespace rosserial_server
34 {
35 
36 const MsgInfo lookupMessage(const std::string& message_type, const std::string submodule)
37 {
38  MsgInfo msginfo;
39  size_t slash_pos = message_type.find('/');
40  if (slash_pos == std::string::npos)
41  {
42  throw std::runtime_error("Passed message type string does not include a slash character.");
43  }
44  std::string module_name = message_type.substr(0, slash_pos);
45  std::string class_name = message_type.substr(slash_pos + 1, std::string::npos);
46 
47  // For now we initialize and finalize for each message. It's quick to do and avoids
48  // an initialized Python interpreter hanging around for the duration of the execution.
49  Py_Initialize();
50  PyObject* module = PyImport_ImportModule((module_name + "." + submodule).c_str());
51  if (!module)
52  {
53  Py_Finalize();
54  throw std::runtime_error("Unable to import message module " + module_name + ".");
55  }
56  PyObject* msg_class = PyObject_GetAttrString(module, class_name.c_str());
57  if (!msg_class)
58  {
59  Py_Finalize();
60  throw std::runtime_error("Unable to find message class " + class_name +
61  " in module " + module_name + ".");
62  }
63  Py_XDECREF(module);
64 
65  PyObject* full_text = PyObject_GetAttrString(msg_class, "_full_text");
66  PyObject* md5sum = PyObject_GetAttrString(msg_class, "_md5sum");
67  if (!md5sum)
68  {
69  Py_Finalize();
70  throw std::runtime_error("Class for message " + message_type + " did not contain" +
71  "expected _md5sum attribute.");
72  }
73  Py_XDECREF(msg_class);
74 
75 #if PY_VERSION_HEX > 0x03000000
76  if (full_text)
77  {
78  msginfo.full_text.assign(PyUnicode_AsUTF8(full_text));
79  }
80  msginfo.md5sum.assign(PyUnicode_AsUTF8(md5sum));
81 #else
82  if (full_text)
83  {
84  msginfo.full_text.assign(PyString_AsString(full_text));
85  }
86  msginfo.md5sum.assign(PyString_AsString(md5sum));
87 #endif
88 
89  // See https://github.com/ros/ros_comm/issues/344
90  // and https://github.com/ros/gencpp/pull/14
91  // Valid full_text returned, but it is empty, so insert single line
92  if (full_text && msginfo.full_text.empty())
93  {
94  msginfo.full_text = "\n";
95  }
96 
97  Py_XDECREF(full_text);
98  Py_XDECREF(md5sum);
99  Py_Finalize();
100 
101  return msginfo;
102 }
103 
104 } // namespace rosserial_server
#define PyUnicode_AsUTF8
const char * md5sum()
const MsgInfo lookupMessage(const std::string &message_type, const std::string submodule="msg")
Definition: msg_lookup.cpp:36


rosserial_server
Author(s): Mike Purvis
autogenerated on Mon Feb 28 2022 23:35:31