只要做到在用Cython你会用C做同样的事情,直接调用PyCObject_FromVoidPtrAndDesc
。以下是从您的链接移植到Cython的示例:
###### example.pyx ######
from libc.stdlib cimport malloc, free
from cpython.cobject cimport PyCObject_FromVoidPtrAndDesc
cdef int _shift_function(int *output_coordinates, double* input_coordinates,
int output_rank, int input_rank, double *shift_data):
cdef double shift = shift_data[0]
cdef int ii
for ii in range(input_rank):
input_coordinates[ii] = output_coordinates[ii] - shift
return 1
cdef void _shift_destructor(void* cobject, void *shift_data):
free(shift_data)
def shift_function(double shift):
"""This is the function callable from python."""
cdef double* shift_data = <double*>malloc(sizeof(shift))
shift_data[0] = shift
return PyCObject_FromVoidPtrAndDesc(&_shift_function,
shift_data,
&_shift_destructor)
性能应与纯C版本相同。
请注意,Cyhton要求运营商&
获取函数地址。另外,Cython缺少指针取消引用运算符*
,而是使用索引等价物(*ptr
- >ptr[0]
)。
+1只是指针笑话:-p – Will 2013-05-08 14:16:55
这似乎是正确的做! :D – 2013-05-08 14:50:50