[Pyrex] Cannot cdef __init__?

Andrew Bennetts andrew-pyrex at puzzling.org
Sun Jan 18 04:44:30 CET 2004


I'm trying to wrap a library with Pyrex, but I've encountered a problem.
I've got an extenstion type that I'd like to initialise with a c type, i.e.

cdef class MyClass:
    cdef typefromlibrary *x

    cdef __init__(self, typefromlibrary *x):
        self.x = x
    
    ...

But this doesn't work.

Here's a complete example that I think should work, but doesn't:

-----
ctypedef int size_t

cdef extern from "malloc.h":
    void* malloc(size_t size)
    void free(void* ptr)

cdef struct pair:
    int x
    int y

cdef class Fred:
    cdef pair *p
    
    cdef __init__(self, pair *p):
        self.p = p
        
    def foo(self):
        return self.p.x + self.p.y

def test(a, b):
    cdef pair *p

    p = <pair *> malloc(sizeof(pair))
    p.x = a
    p.y = b
    
    return Fred(p)
-----

With this code, pyrexc tells me:

/home/andrew/code/crap/pyrex_init_test.pyx:27:16: Cannot convert 'pair (*)' to Python object

But I don't want it to be converted! :)

If I don't use an extenstion type, I get the sort of behaviour I'd expect --
but I really would like a proper type.

-----
ctypedef int size_t

cdef extern from "malloc.h":
    void* malloc(size_t size)
    void free(void* ptr)

cdef struct pair:
    int x
    int y

cdef int foo(pair *p):
    return p.x + p.y

def test(a, b):
    cdef pair *p

    p = <pair *> malloc(sizeof(pair))
    p.x = a
    p.y = b
    
    return foo(p)
-----

I've also tried with __new__, but the result is the same.

Is there some way to initialise a class with a c variable that I don't know
about?  Or am I misunderstanding something more fundamental?

-Andrew.





More information about the Pyrex mailing list