Skip to main content
 首页 » 编程设计

python之在 Cython 的结构中使用指针数组

2025年05月04日7xing901022

我正在尝试围绕 C 库编写一个 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 

这失败了:

Cannot convert 'void *' to Python object.

显然,Cython 不能确定 self.__stuff.output 总是一个指针。但是我声明了它的类型并且这个类是一个“cdef”类,所以我不太明白为什么。

请您参考如下方法:

问题是 NULL 和 double ** 不兼容。您可以将其分配给 char、int 或 void *,例如:

包装器.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; 
}; 

主.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 

不分配它会崩溃...