2014-09-12 83 views
2

我想圍繞C庫編寫一個Cython包裝。我對Cython非常陌生,所以如果問題很明顯,我很抱歉。在Cython的一個結構中使用指針數組

在文件wrapper.pxd,我定義一個結構(例如降低):

cdef extern from "thiscouldbeyourlibrary.h": 
    cdef struct foo: 
     double **output 

我然後有一個類:

cdef class Bar: 
    cdef wrapper.foo __stuff 

    cdef do_something(self): 
     self.__stuff.output = NULL 

此失敗:

無法將'void *'轉換爲Python對象。

顯然,Cython不能確定self .__ stuff.output總是一個指針。但是我聲明瞭它的類型,這個類是一個「cdef」類,所以我不明白爲什麼。

+0

注意,有用於發電的具體任務更好的工具* Python包裝*,如[SWIG( http://www.swig.org/)(這是'pywin32'使用的)。 – 2014-09-12 16:08:47

+0

@ivan_pozdeev我知道。基於SWIG,實際上已經有了我需要的特定庫的包裝。但是,我遇到了一些問題(並且我指的是segfaults),它並不是我想要的(NumPy互操作性)。 – EyPandaBear 2014-09-12 16:17:34

+0

只是一個猜測:使用'None'而不是'NULL' - 這看起來更像是一個「Python對象」:^) – 2014-09-12 23:17:32

回答

0

問題是NULLdouble **之間的不兼容性。你可以將其分配給charintvoid *,例如,做:

wrapper.pyd:

cdef extern from "thiscouldbeyourlibrary.h": 
    cdef struct foo: 
     char a 
     int b 
     void *c 
     double **output 

thiscouldbeyourlibrary.h:

struct foo 
{ 
    char a; 
    int b; 
    void *c; 
    double **output; 
}; 

main.pyx:

cimport wrapper 

cdef class Bar: 
    cdef wrapper.foo __stuff 
    def __init__(self): 
     self.__stuff.a = <char>NULL 
     self.__stuff.b = <int>NULL 
     self.__stuff.c = NULL 

def main(): 
    bar = Bar() 
    print bar.__stuff.a 
    print bar.__stuff.b 

如果您已經分配了內存爲output之前,你可以做它:

self.__stuff.output[0] = NULL 

不分配就會死機......