如何从 Cython 调用 C-API 函数,例如 PyUnicode_READ_CHAR?

问题描述

我正在使用 Cython 来加速对字符串进行操作的函数(unicode,cpython 3.6)。

如何从我的 Cython Py_UCS4 val = PyUnicode_READ_CHAR(my_string,my_index) 代码调用 cpython 的 .pyx?我无法找出从 Cython 导入和使用 C-API 的正确方法

谢谢!

解决方法

Cython 没有将整个 CPython 的 C-API 包装在 cpython.*-headers 中,只有最重要的部分。如果一个函数没有被包装,它可以随时完成,例如:

#instead of from cpython.unicode cimport PyUnicode_READ_CHAR
cdef extern from *:
    Py_UCS4 PyUnicode_READ_CHAR(object o,Py_ssize_t index)

之后该函数就可以在 Cython 中使用了。