[pypy-commit] pypy ffistruct: start to implement _ffi.Structure

antocuni noreply at buildbot.pypy.org
Tue Sep 6 18:04:37 CEST 2011


Author: Antonio Cuni <anto.cuni at gmail.com>
Branch: ffistruct
Changeset: r47108:6fe3c422d545
Date: 2011-09-05 16:37 +0200
http://bitbucket.org/pypy/pypy/changeset/6fe3c422d545/

Log:	start to implement _ffi.Structure

diff --git a/pypy/module/_ffi/app_struct.py b/pypy/module/_ffi/app_struct.py
new file mode 100644
--- /dev/null
+++ b/pypy/module/_ffi/app_struct.py
@@ -0,0 +1,29 @@
+class Field(object):
+
+    def __init__(self, name, ffitype):
+        self.name = name
+        self.ffitype = ffitype
+        self.offset = -1
+
+class MetaStructure(type):
+
+    def __new__(cls, name, bases, dic):
+        cls._compute_shape(dic)
+        return type.__new__(cls, name, bases, dic)
+
+    @classmethod
+    def _compute_shape(cls, dic):
+        fields = dic.get('_fields_')
+        if fields is None:
+            return
+        size = 0
+        for field in fields:
+            field.offset = size # XXX: alignment!
+            size += field.ffitype.sizeof()
+            dic[field.name] = field
+        dic['_size_'] = size
+
+
+class Structure(object):
+
+    __metaclass__ = MetaStructure
diff --git a/pypy/module/_ffi/test/test_struct.py b/pypy/module/_ffi/test/test_struct.py
new file mode 100644
--- /dev/null
+++ b/pypy/module/_ffi/test/test_struct.py
@@ -0,0 +1,19 @@
+from pypy.module._ffi.test.test__ffi import BaseAppTestFFI
+
+class AppTestStruct(BaseAppTestFFI):
+
+    def test_compute_shape(self):
+        from _ffi import Structure, Field, types
+        class Point(Structure):
+            _fields_ = [
+                Field('x', types.slong),
+                Field('y', types.slong),
+                ]
+
+        longsize = types.slong.sizeof()
+        assert isinstance(Point.x, Field)
+        assert isinstance(Point.y, Field)
+        assert Point.x.offset == 0
+        assert Point.y.offset == longsize
+        assert Point._size_ == longsize*2
+        


More information about the pypy-commit mailing list