Mar*_*son 40 python string pyobject
我有一个C python扩展,我想打印一些诊断.
我收到一个字符串作为PyObject*.
获取此对象的字符串rep的规范方法是什么,这样它可以用作const char*?
更新:澄清以强调访问为const char*.
pio*_*kuc 45
使用PyObject_Repr(模仿Python的repr功能)或PyObject_Str(模仿str),然后调用PyString_AsStringget char *(你可以,通常应该使用它const char*,例如:
PyObject* objectsRepresentation = PyObject_Repr(yourObject);
const char* s = PyString_AsString(objectsRepresentation);
Run Code Online (Sandbox Code Playgroud)
这种方法对任何人都可以PyObject.如果您完全确定yourObject是Python字符串而不是其他内容(例如数字),则可以跳过第一行并执行以下操作:
const char* s = PyString_AsString(yourObject);
Run Code Online (Sandbox Code Playgroud)
Rom*_*net 26
如果您使用的是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);
}
Run Code Online (Sandbox Code Playgroud)
小智 5
如果您只需要在 Python 3 中打印对象,您可以使用以下函数之一:
static void print_str(PyObject *o)
{
PyObject_Print(o, stdout, Py_PRINT_RAW);
}
static void print_repr(PyObject *o)
{
PyObject_Print(o, stdout, 0);
}
Run Code Online (Sandbox Code Playgroud)