EyPandaBear
EyPandaBear

Reputation: 31

Using a pointer array within a struct in Cython

I am trying to write a Cython wrapper around a C library. I am very new to Cython, so my apologies in advance if the problem is obvious.

In a file wrapper.pxd, I define a struct (reduced example):

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

I then have a class:

cdef class Bar:
    cdef wrapper.foo __stuff

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

This fails:

Cannot convert 'void *' to Python object.

Apparently, Cython cannot be sure that self.__stuff.output is always a pointer. But I declared its type and the class is a "cdef" class, so I don't really understand why.

Upvotes: 3

Views: 854

Answers (1)

Saullo G. P. Castro
Saullo G. P. Castro

Reputation: 58895

The problem is the incompatibility between NULL and double **. You could assign it to a char, int or void *, for example, doing:

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

If you had allocated the memory for output before, you could have done it:

self.__stuff.output[0] = NULL

without allocating it will crash...

Upvotes: 1

Related Questions