PyUnicode字符串和C字符串之间的字符串转换是如何工作的?

How Does String Conversion Between PyUnicode String and C String Work?

我有一个 PyUnicode 对象,我正在尝试将其转换回 C 字符串 (char *)。

我尝试的方法似乎不起作用。这是我的代码:

PyObject * objectCompName = PyTuple_GET_ITEM(compTuple, (Py_ssize_t) 0);
PyObject * ooCompName = PyUnicode_AsASCIIString(objectCompName);
char * compName = PyBytes_AsString(ooCompName);
Py_DECREF(ooCompName);

有什么 another/better 我应该这样做的方法吗?

您需要先将您的 python PyUnicode 转换为非 unicode python 字符串(在此处阅读更多内容:https://docs.python.org/2/c-api/unicode.html#ascii-codecs),然后您可以轻松地将结果转换为 char*

下面是一个伪代码来帮助你继续:

// Assumption: you have a variable named "pyobj" which is
// a pointer to an instance of PyUnicodeObject.

PyObject* temp = PyUnicode_AsASCIIString(pyobj);
if (NULL == temp) {
    // Means the string can't be converted to ASCII, the codec failed
    printf("Oh noes\n");
    return;
}

// Get the actual bytes as a C string
char* c_str = PyByteArray_AsString(temp);

// Use the string in some manner
printf("The python unicode string is: %s\n", c_str);

// Make sure the temp stuff gets cleaned up at the end
Py_XDECREF(temp);

如果UTF-8编码char *没问题,你一定要用PyUnicode_AsUTF8AndSize(需要Python 3.3):

PyObject * objectCompName = PySequence_GetItem(compTuple, 0);
if (! objectCompName) {
    return NULL;
}

Py_ssize_t size;
char *ptr = PyUnicode_AsUTF8AndSize(objectCompName, &size);
if (!ptr) {
    return NULL;
}

// notice that the string pointed to by ptr is not guaranteed to stay forever,
// and you need to copy it, perhaps by `strdup`.

此外,请理解 强制性 检查您在代码中执行的每个 Py* 函数调用的 return 值。

此处 PyTuple_GetItem 将 return NULL 如果 compTuple 不是 tuple,或者 0 导致 IndexError .如果 objectCompName 不是 str 对象,PyUnicode_AsUTF8AndSize 将 return NULL。忽略 return 值,当条件正确时,CPython 与 SIGSEGV 崩溃。