[Pyrex] public extension type to replace a complex structure variable

Greg Ewing greg.ewing at canterbury.ac.nz
Mon Feb 21 03:06:00 CET 2005


Daehyok Shin wrote:
 >
 > The example I sent is just a extremely simplified one.
 > The actual structure has a pointer to very deep hiearchical structures,
 > and a lot of legacy C programs assumed the pointer-linked structures.
 > In the case, is there no way to keep the C pointer in BigObject?
 > Nobody here wants to change the legacy C code.

Yes, you certainly can. Your example misled me a bit -- it
looked like you were trying to implement a data structure
from scratch using extension types, whereas it appears you
really want to *wrap* and existing data structure.

In that case you will need something like this:

   cdef class BigObject:
     cdef bigobject *c_big

     def __new__(self, int ID, int num_smallobjects):
       self.c_big = c_call_to_create_a_bigobject(ID, num_smallobjects)

     def get_smallobject(int i):
       cdef SmallObject small
       small = SmallObject()
       small.c_small = c_call_to_get_ith_small_object(self.c_big, i)
       return small

     # More methods for operating on a bigobject


   cdef class SmallObject:
     cdef smallobject *c_small

     def __init__(self, ID = None):
       if ID is not None:
         # Python code is calling SmallObject constructor
         self.c_small = c_call_to_create_a_smallobject(ID)
       else:
         # Pyrex code is creating a wrapper for an
         # existing smallobject
         pass

     # More methods for operating on a smallobject


The idea is that you have an extension type corresponding
to each C type that you want to expose, with methods that
make calls to the underlying C code for performing
operations on it.

Note that the SmallObject's __new__ method allows it to
be called without arguments, in which case it leaves the
C pointer uninitialised so it can be filled in with a
pointer to an existing smallobject. This is obviously
not entirely safe, since there's nothing stopping Python
code from calling it that way and ending up with an
invalid SmallObject that will lead to a crash. There
are ways of fixing that, but this message is long
enough -- ask me if you want more details.

-- 
Greg Ewing, Computer Science Dept, +--------------------------------------+
University of Canterbury,	   | A citizen of NewZealandCorp, a	  |
Christchurch, New Zealand	   | wholly-owned subsidiary of USA Inc.  |
greg.ewing at canterbury.ac.nz	   +--------------------------------------+



More information about the Pyrex mailing list