[pypy-commit] pypy py3.5: test and "fix" with ample comments about the memoryview() of a ctypes object

arigo pypy.commits at gmail.com
Thu Feb 16 10:04:08 EST 2017


Author: Armin Rigo <arigo at tunes.org>
Branch: py3.5
Changeset: r90164:cb5fc958f45b
Date: 2017-02-16 14:08 +0100
http://bitbucket.org/pypy/pypy/changeset/cb5fc958f45b/

Log:	test and "fix" with ample comments about the memoryview() of a
	ctypes object

diff --git a/pypy/module/_rawffi/buffer.py b/pypy/module/_rawffi/buffer.py
--- a/pypy/module/_rawffi/buffer.py
+++ b/pypy/module/_rawffi/buffer.py
@@ -17,8 +17,18 @@
     def getformat(self):
         return self.datainstance.fmt
 
-    def getitemsize(self):
-        return self.datainstance.itemsize
+    #XXX we keep the default of 1 for now.  I *think* it does not make
+    # sense to give another answer here without also tweaking the
+    # 'shape' and 'strides'.  At least it makes memoryobject.py think the
+    # buffer is not C-contiguous, which is nonsense (e.g. cast() are
+    # refused).  Now, the memoryview we get from a ctypes object is the
+    # one that would correspond to an array of chars of the same
+    # size---which is wrong, because ctypes gives a more complicated
+    # result on CPython (at least 3.5), but at least it corresponds to
+    # the basics.  (For example, CPython 3.5 gives a zero-dimensional
+    # memoryview if the ctypes type is not an array.)
+    #def getitemsize(self):
+    #    return self.datainstance.itemsize
 
     def getitem(self, index):
         ll_buffer = self.datainstance.ll_buffer
diff --git a/pypy/objspace/std/test/test_memoryobject.py b/pypy/objspace/std/test/test_memoryobject.py
--- a/pypy/objspace/std/test/test_memoryobject.py
+++ b/pypy/objspace/std/test/test_memoryobject.py
@@ -8,7 +8,7 @@
 from pypy.conftest import option
 
 class AppTestMemoryView:
-    spaceconfig = dict(usemodules=['array', 'sys'])
+    spaceconfig = dict(usemodules=['array', 'sys', '_rawffi'])
 
     def test_basic(self):
         v = memoryview(b"abc")
@@ -280,6 +280,18 @@
         assert m2.itemsize == m1.itemsize
         assert m2.shape == m1.shape
 
+    def test_cast_ctypes(self):
+        import _rawffi, sys
+        a = _rawffi.Array('i')(1)
+        a[0] = 0x01234567
+        m = memoryview(a).cast('B')
+        if sys.byteorder == 'little':
+            expected = 0x67, 0x45, 0x23, 0x01
+        else:
+            expected = 0x01, 0x23, 0x45, 0x67
+        assert (m[0], m[1], m[2], m[3]) == expected
+        a.free()
+
 class MockBuffer(Buffer):
     def __init__(self, space, w_arr, w_dim, w_fmt, \
                  w_itemsize, w_strides, w_shape):


More information about the pypy-commit mailing list