C++ 将Python异常转换为std::string

C++ 将Python异常转换为std::string,c++,string,exception,python-3.x,converter,C++,String,Exception,Python 3.x,Converter,如何将发生的Python异常转换并保存为std::string或wstring?这是我当前的代码: String ScriptErrorHandler::the_error() { if(PyErr_Occurred()) { PyObject *error_type, *the_error, *the_traceback, *py_error_string, *py_error_unicode; P

如何将发生的Python异常转换并保存为std::string或wstring?这是我当前的代码:

    String ScriptErrorHandler::the_error()
    {
        if(PyErr_Occurred())
        {
            PyObject *error_type, *the_error, *the_traceback, *py_error_string, *py_error_unicode;
            PyErr_Fetch(&error_type, &the_error, &the_traceback);
            PyErr_NormalizeException(&error_type, &the_error, &the_traceback);
            if((error_type != NULL))
            {
                String the_error_string, the_traceback_string;
                if (the_error != NULL)
                {

                        py_error_string = PyObject_Str(the_error);
                        py_error_unicode = PyUnicode_FromObject(py_error_string);
                        const char* char_string = PyUnicode_AS_DATA(py_error_unicode);
                        auto char_length = PyUnicode_GET_DATA_SIZE(py_error_string);
                        the_error_string = String(char_string, char_length);
                }
                if(the_traceback != NULL)
                    auto the_traceback_string = PyBytes_AsString(the_traceback);
                String str_error(the_error_string);
                String str_traceback(the_traceback_string);
                String message(str_error + "\n Traceback: " + str_traceback);
                Py_XDECREF(error_type);
                Py_XDECREF(the_error);
                Py_XDECREF(the_traceback);
                return message;
            }
        }
        return StringUtil::BLANK;
    }
调试显示_error_字符串仅包含“i”,它是错误消息的第一个字符,应该类似于“invalid..blabla”

我做错了什么


我使用的是Python3.1,看起来您试图将Unicode字符串解释为ASCII。第一个字符的顶部字节将被解释为NUL终止符,解释您看到的输出。