我正在尝试调用 qsort
在 Cython 中使用自定义比较函数,但我不明白如何传递函数引用。首先,我有一个结构:
cdef struct Pair:
int i,j
float h
比较函数按
h
排序:cdef int compare(const_void *a, const_void *b):
cdef float v = ((<Pair*>a)).h-((<Pair*>b)).h
if v < 0: return -1
if v > 0: return 1
return 0
这是我遇到麻烦的部分:
cdef Pair[5] pa
for i in range(5):
pa[i].i = i;
pa[i].j = i*2;
pa[i].h = i*.5;
qsort(pa,5,sizeof(Pair),compare)
最后一行不会编译并生成此错误,我认为这与我无法弄清楚如何通过
compare
的事实有关。作为引用 qsort
:Cannot assign type 'int (const_void *, const_void *)' to 'int (*)(const_void *, const_void *) nogil'
最佳答案
我无法重现您的错误。您使用的代码是正确的,并且可以使用 Cython 0.15。我看到的唯一可能是您的错误的是附加到类型的“gil”。如果您想明确将导入的方法声明为“gil safe”,请在声明末尾附加“nogil”。
(请注意,您可以使用 cython -a 检查您的 python 代码,然后打开网络浏览器)
来自“stdlib.h”的 cdef extern:
ctypedef void const_void "const void"
void qsort(void *base, int nmemb, int size,
int(*compar)(const_void *, const_void *))
cdef 结构对:
整数 i,j
float h
cdef int 比较(const_void *a,const_void *b):
cdef float v = ((a)).h-((b)).h
print 'do something with', v
如果 v 0:返回 1
返回 0
定义 r():
cdef 对[5] pa
对于范围内的 i (5):
帕[i].i = i;
pa[i].j = i*2;
pa[i].h = i*.5;
打印'调用qsort'
qsort(pa,5,sizeof(Pair),比较)
print '调用 qsort 完成'
r()
此代码段编译为:
$ cython--版本
Cython 0.15 版
$ cython --embed test.pyx
$ gcc -I/usr/include/python2.7 -Wall -std=c99 test.c -lpython2.7
$ ./a.out
调用 qsort
用 -0.5 做某事
用 -0.5 做某事
用 -0.5 做某事
用 -1.0 做某事
用 -0.5 做某事
调用 qsort 完成
关于cython - 如何将指针传递给 Cython 中的 c 函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8353076/