2011-12-02 34 views
13

Özel bir karşılaştırma fonksiyonu ile Cython aramayı qsort çalışıyorum ama işlev başvuru geçmek anlamıyorum.nasıl Cython bir c işlev işaretçisi geçmek?

cdef struct Pair: 
    int i,j 
    float h 

h tarafından işlev türlü karşılaştırmak:

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) 

son satırı kazandı:

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 

Bu benim sorun yaşıyorum parçasıdır Birincisi, bir yapı var t derleme' ve ben qsort için bir referans olarak compare geçmesine anlamaya olamaz gerçeği ile ilgilidir inanıyoruz, bu hata üretir:

Cannot assign type 'int (const_void *, const_void *)' to 'int (*)(const_void *, const_void *) nogil' 

cevap

9

Ben senin hatayı yeniden edemedik ettik. Kullandığınız kod doğru ve Cython 0.15 ile çalışıyor. Ben o olabilir gördüğüm tek şey hata türüne eklenen "gil" dir. Özellikle "gil güvenli" olarak ithal yöntem bildirmek istiyorsanız, bildirinin sonunda "nogil" ekleyin.

olarak

(eğer Cython -a, daha sonra açık web tarayıcısı ile piton kodunu kontrol edebilirsiniz notu)

 
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() 

Bu pasajı derlenmektedir: Bir [Cython yazı] sahip

 
$ 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 
+0

(http://stackoverflow.com/questions/41944883/verifying-compatibility-in-compiling-extension-types-and-using-them-with-cdef) hakkında bilgi sağlayabilirsiniz. – Phillip

İlgili konular