python - Python 中的 C 扩展 : Conver wchar string to Python Value

标签 python python-c-extension

在 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_FromUnicodePy_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/

相关文章:

python - 使用 heapq.merge 编写排序输出的奇怪 Python 版本相关行为

python - 如何编写Python单元测试列名是字符串?

Python C 扩展 : Extract parameter from the engine

python - 从 Python 中返回 include 和 runtime lib 目录

python - ctypes.ArgumentError : Don't know how to convert parameter

Python C 扩展 - 错误 `python3.6' : free(): invalid pointer: 0x

python - 如何在python中将列表小写

python - 在同一个 CSV 文件中保存不同大小的多个列/变量

python - 如何根据Python列表中出现在该元素之前的元素来访问该元素

python - 在 C 中嵌入 Python,链接失败, undefined reference `Py_Initialize'