在Cython中使用结构体内的指针数组

3 投票
1 回答
835 浏览
提问于 2025-04-21 08:21

我正在尝试为一个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

但是这段代码出错了:

无法将 'void *' 转换为Python对象。

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

1 个回答

1

这个问题是因为 NULLdouble ** 之间不兼容。你可以把 NULL 赋值给 charint 或者 void *,比如这样做:

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

如果没有分配内存,程序会崩溃...

撰写回答