Commits

Armin Rigo committed 8643231

ffi.string() with two arguments.

Comments (0)

Files changed (4)

 Windows: GetLastError()
-ffi.string()
 Windows: __stdcall support, ideally automatically detected
 reading "static const" variables from cdefs?
 ffi.gc()?
         BType = self.typeof(cdecl)
         return BType._cast_from(source)
 
+    def string(self, pointer, length):
+        return self._backend.string(pointer, length)
+
     def _parse_type(self, cdecl):
         try:
             return self._cached_parsed_types[cdecl]

ffi/backend_ctypes.py

     def set_errno(self, value):
         ctypes.set_errno(value)
 
+    def string(self, bptr, length):
+        if not (isinstance(bptr, CTypesGenericPtr) and bptr._automatic_casts):
+            raise TypeError("'void *' argument expected, got %r" %
+                            (type(bptr).__name__,))
+        p = ctypes.cast(bptr._as_ctype_ptr, ctypes.POINTER(ctypes.c_char))
+        return ''.join([p[i] for i in range(length)])
+
 
 class CTypesLibrary(object):
 

testing/backend_tests.py

         assert (p+5) - (p+1) == 4
         assert p == s+0
         assert p+1 == s+1
+
+    def test_ffi_string(self):
+        ffi = FFI(backend=self.Backend())
+        a = ffi.new("int[]", range(100, 110))
+        s = ffi.string(ffi.cast("void *", a), 8)
+        assert type(s) is str
+        if sys.byteorder == 'little':
+            assert s == '\x64\x00\x00\x00\x65\x00\x00\x00'
+        else:
+            assert s == '\x00\x00\x00\x64\x00\x00\x00\x65'