3 def empty_decorator(x):
6 def locals(**arg_types):
23 # Emulated language constructs
26 if hasattr(type, '__call__'):
35 return pointer(type(arg))([arg])
37 def declare(type=None, value=None, **kwds):
38 if type is not None and hasattr(type, '__call__'):
48 class CythonType(object):
50 def _pointer(self, n=1):
55 def __getitem__(self, ix):
56 return array(self, ix)
59 class PointerType(CythonType):
61 def __init__(self, value=None):
62 if isinstance(value, ArrayType):
63 self._items = [cast(self._basetype, a) for a in value._items]
64 elif isinstance(value, list):
65 self._items = [cast(self._basetype, a) for a in value]
71 def __getitem__(self, ix):
73 raise IndexError("negative indexing not allowed in C")
74 return self._items[ix]
76 def __setitem__(self, ix, value):
78 raise IndexError("negative indexing not allowed in C")
79 self._items[ix] = cast(self._basetype, value)
81 class ArrayType(PointerType):
84 self._items = [None] * self._n
87 class StructType(CythonType):
89 def __init__(self, **data):
90 for key, value in data.iteritems():
91 setattr(self, key, value)
93 def __setattr__(self, key, value):
94 if key in self._members:
95 self.__dict__[key] = cast(self._members[key], value)
97 raise AttributeError("Struct has no member '%s'" % key)
100 class UnionType(CythonType):
102 def __init__(self, **data):
104 raise AttributeError("Union can only store one field at a time.")
105 for key, value in data.iteritems():
106 setattr(self, key, value)
108 def __setattr__(self, key, value):
109 if key in '__dict__':
110 CythonType.__setattr__(self, key, value)
111 elif key in self._members:
112 self.__dict__ = {key: cast(self._members[key], value)}
114 raise AttributeError("Union has no member '%s'" % key)
116 def pointer(basetype):
117 class PointerInstance(PointerType):
119 return PointerInstance
121 def array(basetype, n):
122 class ArrayInstance(ArrayType):
127 def struct(**members):
128 class StructInstance(StructType):
131 setattr(StructInstance, key, None)
132 return StructInstance
134 def union(**members):
135 class UnionInstance(UnionType):
138 setattr(UnionInstance, key, None)
141 class typedef(CythonType):
143 def __init__(self, type):
144 self._basetype = type
146 def __call__(self, value=None):
147 if value is not None:
148 value = cast(self._basetype, value)
157 except NameError: # Py3
163 int_types = ['char', 'short', 'int', 'long', 'longlong', 'Py_ssize_t']
164 float_types = ['double', 'float']
165 other_types = ['bint', 'Py_ssize_t', 'void']
168 for name in int_types:
169 gs[name] = typedef(py_int)
170 gs['u'+name] = typedef(py_int)
172 double = float = typedef(py_float)
176 for t in int_types + float_types + other_types:
177 for i in range(1, 4):
178 gs["%s_%s" % ('p'*i, t)] = globals()[t]._pointer(i)