Caffe2 - C++ API
A deep learning, cross platform ML framework
python_strings.h
1 #pragma once
2 
3 #include <torch/csrc/python_headers.h>
4 #include <stdexcept>
5 #include <string>
6 #include <torch/csrc/utils/object_ptr.h>
7 
8 // Utilities for handling Python strings. Note that PyString, when defined, is
9 // the same as PyBytes.
10 
11 // Returns true if obj is a bytes/str or unicode object
12 // As of Python 3.6, this does not require the GIL
13 inline bool THPUtils_checkString(PyObject* obj) {
14  return PyBytes_Check(obj) || PyUnicode_Check(obj);
15 }
16 
17 // Unpacks PyBytes (PyString) or PyUnicode as std::string
18 // PyBytes are unpacked as-is. PyUnicode is unpacked as UTF-8.
19 // NOTE: this method requires the GIL
20 inline std::string THPUtils_unpackString(PyObject* obj) {
21  if (PyBytes_Check(obj)) {
22  size_t size = PyBytes_GET_SIZE(obj);
23  return std::string(PyBytes_AS_STRING(obj), size);
24  }
25  if (PyUnicode_Check(obj)) {
26 #if PY_MAJOR_VERSION == 2
27  THPObjectPtr bytes(PyUnicode_AsUTF8String(obj));
28  if (!bytes) {
29  throw std::runtime_error("error unpacking string as utf-8");
30  }
31  size_t size = PyBytes_GET_SIZE(bytes.get());
32  return std::string(PyBytes_AS_STRING(bytes.get()), size);
33 #else
34  Py_ssize_t size;
35  const char* data = PyUnicode_AsUTF8AndSize(obj, &size);
36  if (!data) {
37  throw std::runtime_error("error unpacking string as utf-8");
38  }
39  return std::string(data, (size_t)size);
40 #endif
41  }
42  throw std::runtime_error("unpackString: expected bytes or unicode object");
43 }
44 
45 inline PyObject* THPUtils_packString(const char* str) {
46 #if PY_MAJOR_VERSION == 2
47  return PyString_FromString(str);
48 #else
49  return PyUnicode_FromString(str);
50 #endif
51 }
52 
53 inline PyObject* THPUtils_packString(const std::string& str) {
54 #if PY_MAJOR_VERSION == 2
55  return PyString_FromStringAndSize(str.c_str(), str.size());
56 #else
57  return PyUnicode_FromStringAndSize(str.c_str(), str.size());
58 #endif
59 }