Python: get string representation of PyObject?

前端 未结 5 1345
予麋鹿
予麋鹿 2020-12-23 19:41

I\'ve got a C python extension, and I would like to print out some diagnostics.

I\'m receiving a string as a PyObject*.

What\'s the canonical way to obtain a

5条回答
  •  北海茫月
    2020-12-23 20:12

    Here is the correct answer if you are using Python 3:

    static void reprint(PyObject *obj) {
        PyObject* repr = PyObject_Repr(obj);
        PyObject* str = PyUnicode_AsEncodedString(repr, "utf-8", "~E~");
        const char *bytes = PyBytes_AS_STRING(str);
    
        printf("REPR: %s\n", bytes);
    
        Py_XDECREF(repr);
        Py_XDECREF(str);
    }
    

提交回复
热议问题