Commits

Armin Rigo  committed d9f62ad

str() of 'char[]' and 'char*'.

  • Participants
  • Parent commits a5dbee2

Comments (0)

Files changed (2)

File ffi/backend_ctypes.py

             if kind == 'char':
                 def __int__(self):
                     return ord(self._value)
+                def __str__(self):
+                    return self._value
                 __nonzero__ = __int__
             else:
                 def __nonzero__(self):
         return CTypesPrimitive
 
     def new_pointer_type(self, BItem):
+        if BItem is self.get_cached_btype('new_primitive_type', 'char'):
+            kind = 'char'
+        else:
+            kind = 'generic'
         #
         class CTypesPtr(CTypesData):
             _ctype = ctypes.POINTER(BItem._ctype)
             def __setitem__(self, index, value):
                 self._as_ctype_ptr[index] = BItem._to_ctypes(value)
 
+            if kind == 'char':
+                def __str__(self):
+                    n = 0
+                    while self._as_ctype_ptr[n] != '\x00':
+                        n += 1
+                    return ''.join([self._as_ctype_ptr[i] for i in range(n)])
+
             @staticmethod
             def _to_ctypes(value):
                 if value is None:
             brackets = ' &[]'
         else:
             brackets = ' &[%d]' % length
+        if BItem is self.get_cached_btype('new_primitive_type', 'char'):
+            kind = 'char'
+        else:
+            kind = 'generic'
         #
         class CTypesArray(CTypesData):
             if length is not None:
                     raise IndexError
                 self._blob[index] = BItem._to_ctypes(value)
 
+            if kind == 'char':
+                def __str__(self):
+                    return ''.join(self._blob)
+
             def _convert_to_address_of(self, BClass):
                 if BItem is BClass:
                     return ctypes.addressof(self._blob)

File testing/backend_tests.py

         a = ffi.new("int[]", [10, 11, 12, 13, 14])
         assert len(a) == 5
         assert ffi.sizeof(a) == 20
+
+    def test_string_from_char_array(self):
+        ffi = FFI(backend=self.Backend())
+        assert str(ffi.new("char", "x")) == "x"
+        p = ffi.new("char[]", "hello.")
+        p[5] = '!'
+        assert str(p) == "hello!"
+        a = ffi.new("char[]", "hello\x00world")
+        p = ffi.new("char *", a)
+        assert str(p) == 'hello'