如何在Cython扩展类型中使用指向typedef结构的指针

时间:2016-07-12 06:12:54

标签: python cython

说我的头文件typedef struct中有以下example.h

typedef struct A A;

我想在A中创建一个带有test.pyx指针作为类变量的Cython扩展类型,然后在对{{{{}}的引用上调用初始化函数f 1}}:

A

当我编译`test.pyx时,我最终得到以下编译错误:

cdef class Test:
    cdef A* a

    def __cinit__(self):
        self.a = a
        f(&a)
    ...

显然它没有识别对象Error compiling Cython file: ------------------------------------------------------------ ... cdef class Test: cdef A* a def __cinit__(self): self.a = a ^ ------------------------------------------------------------ test.pyx: undeclared name not builtin: a Error compiling Cython file: ------------------------------------------------------------ ... cdef class Test: cdef A* a def __cinit__(self): self.a = a ^ ------------------------------------------------------------ test.pyx: Cannot convert Python object to 'A *' ,而是将它解释为python对象。我该如何解决这个问题?

1 个答案:

答案 0 :(得分:1)

这是因为您必须在使用之前声明它。例如,您的c代码为example.h

typedef struct struct_name{
    int a;
    float b;
}struct_alias;

然后您的.pyx文件应如下所示:

cdef extern from "example.h":
    ctypedef struct struct_alias:
        int a
        int b

cdef class Test:
    cdef A* a

    def __cinit__(self):
        self.a = a
        f(&a)
    ...