我正在尝试打电话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 代码,然后打开网络浏览器)
cdef extern from "stdlib.h":
ctypedef void const_void "const void"
void qsort(void *base, int nmemb, int size,
int(*compar)(const_void *, const_void *)) nogil
cdef struct Pair:
int i,j
float h
cdef int compare(const_void *a, const_void *b):
cdef float v = ((a)).h-((b)).h
print 'do something with', v
if v 0: return 1
return 0
def r():
cdef Pair[5] pa
for i in range(5):
pa[i].i = i;
pa[i].j = i*2;
pa[i].h = i*.5;
print 'call qsort'
qsort(pa,5,sizeof(Pair),compare)
print 'call qsort done'
r()
该片段编译为:
$ cython --version
Cython version 0.15
$ cython --embed test.pyx
$ gcc -I/usr/include/python2.7 -Wall -std=c99 test.c -lpython2.7
$ ./a.out
call qsort
do something with -0.5
do something with -0.5
do something with -0.5
do something with -1.0
do something with -0.5
call qsort done
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)