如何在Cython中将指针传递给c函数? [英] How do I pass a pointer to a c function in Cython?

查看:218
本文介绍了如何在Cython中将指针传递给c函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用自定义比较功能在Cython中调用 qsort ,但是我不知道如何传递函数引用。首先,我有一个结构:

I'm trying call qsort in Cython with a custom compare function but I don't understand how to pass the function reference. First, I have a struct:

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的引用

The last line won't compile and generates this error which I believe is related to the fact that I can't figure out how to pass compare as a reference to qsort:

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


推荐答案

I无法重现您的错误。您使用的代码是正确的,并且可以与Cython 0.15一起使用。我唯一看到的可能是您的错误是该类型后面附加的 gil。如果要专门将导入的方法声明为 gil safe,请在声明末尾附加 nogil。

I've not been able to reproduce your error. The code you're using is right, and working with Cython 0.15. The only thing i see that might be your error is the "gil" appended to the type. If you want to specifically declare a imported method as "gil safe", append "nogil" at the end of the declaration.

(请注意,您可以检查python代码并用cython -a打开,然后打开Web浏览器)

(note that you can check your python code with cython -a , then open web browser for )


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

这篇关于如何在Cython中将指针传递给c函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆