我正在使用 Cython 与外部 C API 交互,该 API 接受 UCS2 格式(wchar 数组)的 unicode 字符串。 (我了解 UCS2 相对于 UTF-16 的局限性,但它是第三方 API。)
- Cython 版本:0.15.1
- Python 版本:2.6(窄 unicode 构建)
- 操作系统:FreeBSD
Cython 用户指南广泛涉及将 unicode 转换为字节字符串,但我不知道如何转换为 16 位数组。我意识到我首先需要编码为 UTF-16(我现在假设 BMP 之外的代码点不会出现)。接下来我该做什么?请帮忙。
提前致谢。
最佳答案
这在 Python 3 上是很有可能的,解决方案是这样的:
# cython: language_level=3
from libc.stddef cimport wchar_t
cdef extern from "Python.h":
wchar_t* PyUnicode_AsWideCharString(object, Py_ssize_t *)
cdef extern from "wchar.h":
int wprintf(const wchar_t *, ...)
my_string = u"Foobar\n"
cdef Py_ssize_t length
cdef wchar_t *my_wchars = PyUnicode_AsWideCharString(my_string, &length)
wprintf(my_wchars)
print("Length:", <long>length)
print("Null End:", my_wchars[7] == 0)
下面是一个不太好的 Python 2 方法,但它可能处理未定义或损坏的行为,所以我不会轻易相信它:
# cython: language_level=2
from cpython.ref cimport PyObject
from libc.stddef cimport wchar_t
from libc.stdio cimport fflush, stdout
from libc.stdlib cimport malloc, free
cdef extern from "Python.h":
ctypedef PyObject PyUnicodeObject
Py_ssize_t PyUnicode_AsWideChar(PyUnicodeObject *o, wchar_t *w, Py_ssize_t size)
my_string = u"Foobar\n"
cdef Py_ssize_t length = len(my_string.encode("UTF-16")) // 2 # cheating
cdef wchar_t *my_wchars = <wchar_t *>malloc(length * sizeof(wchar_t))
cdef Py_ssize_t number_written = PyUnicode_AsWideChar(<PyUnicodeObject *>my_string, my_wchars, length)
# wprintf breaks things for some reason
print [my_wchars[i] for i in range(length)]
print "Length:", <long>length
print "Number Written:", <long>number_written
print "Null End:", my_wchars[7] == 0
free(my_wchars)
关于python - Cython:将 unicode 字符串转换为 wchar 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19650195/