Alex
Alex

Reputation: 4264

How to use pointer to typedef struct in Cython Extension Type

Say I have the following typedef struct in my header file example.h:

typedef struct A A;

I am tring to make a Cython Extension Type with a pointer to A as a class variable in test.pyx, and then I call an initialization function f on a reference to A:

cdef class Test:
    cdef A* a

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

When I compile `test.pyx, I end up with the following compilation errors:

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 *'

Apparently it is not recognizing the object a, and it is interpreting it as a python object. How can I fix this?

Upvotes: 0

Views: 1679

Answers (1)

spacegoing
spacegoing

Reputation: 5306

This is because you have to declare it before you use it. For example you have this in your c code example.h :

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

Then your .pyx file should look like:

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

Upvotes: 2

Related Questions