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

2024-09-25 02:37:13 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个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);

我还有别的/更好的方法吗?在


Tags: 对象方法字符串代码pygetitempyobject
2条回答

如果UTF-8编码的char *是正常的,那么您肯定应该使用^{}(这需要python3.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*函数调用的返回值。在

这里,PyTuple_GetItem将返回{},如果compTuple不是tuple,或者{}导致{}。^如果objectCompName不是str对象,则{}将返回NULL。忽略返回值,当条件正确时,SIGSEGV会导致CPython崩溃。在

您需要首先将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);

相关问题 更多 >