在 Python 的 C 扩展中,我可以使用 Py_BuildValue()
将 char 字符串转换为 Python 值,如下所示:Py_BuildValue("s", str)
。但是,如果字符串是 wchar 数组,则不能使用 Py_BuildValue("s", str)
。
我想我可以像这样使用 PyUnicode:
PyObject* pb=PyUnicode_FromUnicode( (const Py_UNICODE*)(str), wcslen(str) );
PyObject *val = Py_BuildValue("o", pb);
但是,它不起作用。如何将 wchar 字符串转换为 Python 值?
最佳答案
我认为您不需要组合 PyUnicode_FromUnicode
和 Py_BuildValue
。
下面的pb
已经是一个Python unicode对象。
PyObject* pb=PyUnicode_FromUnicode( (const Py_UNICODE*)(str), wcslen(str) );
使用Py_BuildValue
来处理它是多余的,但它是无害的。
我认为您的问题是由格式不正确的 o
引起的。它应该是 O
。
您还可以使用 Py_BuildValue
将 Unicode(UCS-2 或 UCS-4)数据的空终止缓冲区转换为 Python Unicode 对象。
例如:
const wchar_t *w = L"Hello world!";
PyObject* pb = Py_BuildValue("u", w);
更多
关于python - Python 中的 C 扩展 : Conver wchar string to Python Value,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15153497/