[Pyrex] newby guidance

John J Lee jjl at pobox.com
Wed Jun 25 20:14:18 CEST 2003


On Wed, 25 Jun 2003, Robin Becker wrote:

> I want to utilize a large C struct in both pyrex and C. I already have a
> defining header file so the C code just imports the header.
>
> Can I make use of pyrex to create my struct and pass it around to C code
> without defining the struct again in pyrex?
>
> I'm a bit confused about how this all works. I had imagined naively that
> one could somehow just wrap the struct using the header file and add
> methods in pyrex.

I *think* you can use Pyrex extension types to wrap structs without
explicitly declaring the struct members, but in my experiment I ran into
trouble zero-initialising whole structs as you would in C with the {}
aggregate-initialisation syntax.

My first attempt just declared TidyBuffer, without declaring it's members,
but then I found I couldn't initialise it with self.buf = 0 (see below for
context).  I had to add a colon followed by the members to the 'cdef
struct _TidyBuffer', and then initialise the members individually in
Buffer.__new__:

cdef extern from "buffio.h":
    cdef struct _TidyBuffer:
        byte* bp  # pointer to bytes
        uint  size  # bytes currently in use
        uint  allocated  # nr bytes allocated
        uint  next  # offset of current input position

    ctypedef _TidyBuffer TidyBuffer

[...]
cdef class Buffer:
    cdef TidyBuffer buf

    def __new__(self, *args, **kwargs):
        # XXX casting to TidyBuffer here causes C compile error -- is this a
        #   bug (shouldn't Pyrex spot the error, not leave it to the C
        #   compiler)?
##         self.buf = 0
        self.buf.bp = NULL
        self.buf.size = 0
        self.buf.allocated = 0
        self.buf.next = 0

    def __dealloc__(self):
        tidyBufFree(&self.buf)

    def data(self):
        return self.buf.bp


I may as well ask about the XXX there too -- is it always regarded as a
bug if Pyrex doesn't report an error but the C compiler does?  Or is
casting (for example) at one's own risk even at Pyrex-compile time?


John





More information about the Pyrex mailing list