3 def empty_decorator(x):
6 def locals(**arg_types):
23 # Emulated language constructs
26 if hasattr(type, '__call__'):
38 return pointer(type(arg))([arg])
40 def declare(type=None, value=None, **kwds):
41 if type is not None and hasattr(type, '__call__'):
51 class CythonType(object):
53 def _pointer(self, n=1):
58 def __getitem__(self, ix):
59 return array(self, ix)
62 class PointerType(CythonType):
64 def __init__(self, value=None):
65 if isinstance(value, ArrayType):
66 self._items = [cast(self._basetype, a) for a in value._items]
67 elif isinstance(value, list):
68 self._items = [cast(self._basetype, a) for a in value]
74 def __getitem__(self, ix):
76 raise IndexError("negative indexing not allowed in C")
77 return self._items[ix]
79 def __setitem__(self, ix, value):
81 raise IndexError("negative indexing not allowed in C")
82 self._items[ix] = cast(self._basetype, value)
84 class ArrayType(PointerType):
87 self._items = [None] * self._n
90 class StructType(CythonType):
92 def __init__(self, **data):
93 for key, value in data.iteritems():
94 setattr(self, key, value)
96 def __setattr__(self, key, value):
97 if key in self._members:
98 self.__dict__[key] = cast(self._members[key], value)
100 raise AttributeError("Struct has no member '%s'" % key)
103 class UnionType(CythonType):
105 def __init__(self, **data):
107 raise AttributeError("Union can only store one field at a time.")
108 for key, value in data.iteritems():
109 setattr(self, key, value)
111 def __setattr__(self, key, value):
112 if key in '__dict__':
113 CythonType.__setattr__(self, key, value)
114 elif key in self._members:
115 self.__dict__ = {key: cast(self._members[key], value)}
117 raise AttributeError("Union has no member '%s'" % key)
119 def pointer(basetype):
120 class PointerInstance(PointerType):
122 return PointerInstance
124 def array(basetype, n):
125 class ArrayInstance(ArrayType):
130 def struct(**members):
131 class StructInstance(StructType):
134 setattr(StructInstance, key, None)
135 return StructInstance
137 def union(**members):
138 class UnionInstance(UnionType):
141 setattr(UnionInstance, key, None)
144 class typedef(CythonType):
146 def __init__(self, type):
147 self._basetype = type
149 def __call__(self, value=None):
150 if value is not None:
151 value = cast(self._basetype, value)
160 except NameError: # Py3
166 int_types = ['char', 'short', 'int', 'long', 'longlong', 'Py_ssize_t']
167 float_types = ['double', 'float']
168 other_types = ['bint', 'void']
171 for name in int_types:
172 gs[name] = typedef(py_int)
173 gs['u'+name] = typedef(py_int)
175 double = float = typedef(py_float)
179 for t in int_types + float_types + other_types:
180 for i in range(1, 4):
181 gs["%s_%s" % ('p'*i, t)] = globals()[t]._pointer(i)