7

我正在使用 Cython (0.15.2) 为 Python (2.6.5) 创建扩展。我创建了一个 pxd 文件和一个 pyx 文件。这是我的 pyx 文件的内容:

cimport capifuncs

cdef class myArray:
    cdef capifuncs.myArray *_my_array
    def __cinit__(self, size):
        self._my_array = capifuncs.array_new(size)
        if (self._my_array is NULL):
            raise MemoryError()

    def __dealloc__(self):
        if self._my_array is not NULL:
            capifuncs.array_free(self._my_array)

    def __bool__(self):
        return not capifuncs.IsEmpty(self._my_array)


    ##############################
    #        Array methods       #
    ##############################

    cpdef getItem(self, unsigned int pos):
        if capifuncs.IsEmpty(self._my_array):
            raise IndexError("Array is empty")
        #if ():
        #    raise IndexError("Array bounds exceeded")

        return capifuncs.array_get_item(self._my_array, pos)


    cpdef setItem(self, unsigned int pos, double val):
        if capifuncs.IsEmpty(self._my_array):
            raise IndexError("Array is empty")
        #if ():
        #    raise IndexError("Array bounds exceeded")

        capifuncs.array_set_item(self._my_array, pos, val)




# Free functions
cpdef long someCAPIFuncCall(capifuncs.FooBar *fb, capifuncs.myArray *arr, long start, long stop):
    return capifuncs.doSomethingInteresting(fb, arr, start, stop)

如果我注释掉自由(即非成员)函数定义语句,代码会正确编译并生成扩展。但是,如果我取消注释并尝试编译该文件,我会收到以下错误消息:

cafuncs.pyx:64:23:无法将 Python 对象参数转换为类型 'FooBar *'

这是什么原因,我该如何解决?

4

1 回答 1

4

定义为的函数cpdef可从 Python 和 C 调用。

如果参数被声明为 C 数据类型,Cython 将尝试在从 Python 调用时自动转换传递给函数的对象。但是这种转换只适用于数字和字符串类型——所有其他类型都会导致编译时错误。

你的意思是把这个函数暴露给 Python 吗?如果不是,请使用cdef.

否则,您将需要为要传入和传出 Python 的 C 类型创建包装器。有关如何执行此操作的一些示例,请参阅Cython 教程。

于 2011-11-07T19:31:58.900 回答