我正在使用Cython将一个C库包装到Python 3中,并寻找一种将wchar_t字符串转换为Python对象的方法,我希望从函数中返回该对象。这个问题在这个问题的答案中提到,但它涉及将字符串编码为多字节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
是一个有效的字符串。