Commits

Armin Rigo committed b1be163

ffi.sizeof("type")

Comments (0)

Files changed (3)

         typenode = self._parse_type(cdecl)
         return self._get_btype(typenode)
 
+    def sizeof(self, cdecl):
+        BType = self.typeof(cdecl)
+        return BType._get_size()
+
     def new(self, cdecl, init=None):
         BType = self.typeof(cdecl)
         return BType(init)

ffi/backend_ctypes.py

         raise TypeError("cannot convert %r to %r" % (
             self._get_c_name(), BClass._get_c_name(' *')))
 
+    @classmethod
+    def _get_size(cls):
+        return ctypes.sizeof(cls._ctype)
+
 
 class CTypesBackend(BackendBase):
 

testing/backend_tests.py

         ffi = FFI(backend=self.Backend())
         py.test.raises(TypeError, ffi.new, "union baz")
         ffi.new("union baz *")   # this works
+
+    def test_sizeof(self):
+        ffi = FFI(backend=self.Backend())
+        ffi.cdef("""
+            struct foo { int a; short b, c, d; };
+            union foo { int a; short b, c, d; };
+        """)
+        for c_type, expected_size in [
+            ('char', 1),
+            ('unsigned int', 4),
+            ('char *', SIZE_OF_LONG),
+            ('int[5]', 20),
+            ('struct foo', 12),
+            ('union foo', 4),
+            ]:
+            size = ffi.sizeof(c_type)
+            assert size == expected_size