ATLAS Offline Software
PyGetString.h
Go to the documentation of this file.
1 // This file's extension implies that it's C, but it's really -*- C++ -*-.
2 /*
3  * Copyright (C) 2002-2023 CERN for the benefit of the ATLAS collaboration.
4  */
13 #ifndef ROOTUTILS_PYGETSTRING_H
14 #define ROOTUTILS_PYGETSTRING_H
15 
16 #ifdef _POSIX_C_SOURCE
17 # undef _POSIX_C_SOURCE
18 #endif
19 #ifdef _XOPEN_SOURCE
20 # undef _XOPEN_SOURCE
21 #endif
22 #include "Python.h"
23 #include <string>
24 #include <utility>
25 
26 
27 namespace RootUtils {
28 
29 
39 inline
40 std::pair<std::string, bool> PyGetString (PyObject* s)
41 {
42  const char* cstr = PyUnicode_AsUTF8AndSize (s, nullptr);
43  if (!cstr && PyBytes_Check (s)) {
44  PyErr_Clear();
45  cstr = PyBytes_AsString (s);
46  }
47  if (cstr) {
48  return std::make_pair (std::string (cstr), true);
49  }
50  return std::make_pair (std::string(), false);
51 }
52 
53 
54 } // namespace RootUtils
55 
56 
57 #endif // not ROOTUTILS_PYGETSTRING_H
RootUtils
Definition: ILogger.h:20
python.SystemOfUnits.s
int s
Definition: SystemOfUnits.py:131
RootUtils::PyGetString
std::pair< std::string, bool > PyGetString(PyObject *s)
Convert python string -> C++ string for py2 and py3.
Definition: PyGetString.h:40
PyObject
_object PyObject
Definition: IPyComponent.h:26