【问题标题】:Cython - convert wide string (wchar_t *) to Python 3 unicode objectCython - 将宽字符串(wchar_t *)转换为 Python 3 unicode 对象
【发布时间】: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


    【解决方案1】:

    使用 -1 作为 PyUnicode_FromWideChar(result, -1) 的第二个参数(以便函数在内部使用 wcslen),修复了问题。

    所以PyUnicode_FromWideChar 真的要走的路。

    【讨论】:

      猜你喜欢
      • 2014-11-12
      • 2013-11-08
      • 1970-01-01
      • 2015-10-27
      • 1970-01-01
      • 1970-01-01
      • 2011-07-14
      • 1970-01-01
      • 2016-02-01
      相关资源
      最近更新 更多