【发布时间】:2013-05-07 10:12:44
【问题描述】:
我正在使用 Cython 将 C 库包装到 Pyhon 3,并且我正在寻找一种将 wchar_t 字符串转换为我想从函数返回的 python 对象的方法。 this question 中有一个答案,但它涉及将字符串编码为多字节 str,并将其解码回 unicode。我希望有更直接的解决方案。我尝试使用 Python C API 中的PyUnicode_FromWideChar,但我遇到了段错误。这是我的 .pyx 代码:
from cpython.ref cimport PyObject
from libc.stddef cimport wchar_t
cdef extern from "Python.h":
PyObject* PyUnicode_FromWideChar(wchar_t *w, Py_ssize_t size)
cdef extern from "../../src/my_c_lib.h":
wchar_t * myObjToStr(wchar_t * result, size_t size, myObj * obj)
cdef class MyClass:
cdef myObj * ptr
...
def to_str(self):
cdef wchar_t buf[64]
cdef wchar_t * result = myObjToStr(buf, 64, self.ptr)
if result is NULL:
raise Exception("Error converting object to string.")
cdef PyObject * pystr = PyUnicode_FromWideChar(result, 64)
return <object>pystr
result 实际上是指向buf 的指针。这有什么问题?有没有其他不用编码/解码的方法?
编辑:我发现PyUnicode_FromWideChar() 返回NULL,但为什么呢?我检查了,result 是一个有效的 wchar_t * 字符串。
【问题讨论】:
标签: python-3.x cython wchar-t