[Pyrex] public extension type to replace a complex structure
variable
Greg Ewing
greg.ewing at canterbury.ac.nz
Fri Feb 18 02:48:54 CET 2005
Daehyok Shin wrote:
> I want to expose a variable to Python using PyRex public extension type.
> But, the problem is that the variable has quite complex structure.
> Like big_object in the appended program code, the variable contains
> pointers indicating other structure variables (here, small_object).
> I want to replace the original definitions of structures with ones
> generated from public extension type.
Assuming you're able to actually re-design the data
structure (as opposed to wrapping an existing one),
I think what you're after is something like this:
cdef class SmallObject:
cdef public int ID
def __new__(self, ID):
self.ID = ID
cdef class BigObject:
cdef public int ID
cdef public object sobjs
def __new__(self, ID):
cdef int i
self.ID = ID
self.sobjs = []
for i from 0 <= i < 10:
self.sobjs.append(SmallObject(i))
You'll notice that I've used a Python list to hold the
small objects, rather than a C array. That's because
a C array or structure in Pyrex can't hold Python
object references, and the SmallObject instances
are Python objects.
If you need more efficient ways of manipulating the
list, you can include extern declarations for the
various Python/C API functions such as PyList_Append
and use those instead of Python method calls.
By the way, you don't need to declare the extension
type itself as 'public', it will be visible to Python
code anyway. Also you don't need the stuff in square
brackets; that's almost obsolete now except for some
very rare use cases.
--
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