3 #include <torch/csrc/python_headers.h> 6 #include <torch/csrc/utils/object_ptr.h> 13 inline bool THPUtils_checkString(PyObject* obj) {
14 return PyBytes_Check(obj) || PyUnicode_Check(obj);
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);
25 if (PyUnicode_Check(obj)) {
26 #if PY_MAJOR_VERSION == 2 29 throw std::runtime_error(
"error unpacking string as utf-8");
31 size_t size = PyBytes_GET_SIZE(bytes.get());
32 return std::string(PyBytes_AS_STRING(bytes.get()), size);
35 const char* data = PyUnicode_AsUTF8AndSize(obj, &size);
37 throw std::runtime_error(
"error unpacking string as utf-8");
39 return std::string(data, (
size_t)size);
42 throw std::runtime_error(
"unpackString: expected bytes or unicode object");
45 inline PyObject* THPUtils_packString(
const char* str) {
46 #if PY_MAJOR_VERSION == 2 47 return PyString_FromString(str);
49 return PyUnicode_FromString(str);
53 inline PyObject* THPUtils_packString(
const std::string& str) {
54 #if PY_MAJOR_VERSION == 2 55 return PyString_FromStringAndSize(str.c_str(), str.size());
57 return PyUnicode_FromStringAndSize(str.c_str(), str.size());