[New-bugs-announce] [issue15944] memoryviews and ctypes

David Beazley report at bugs.python.org
Fri Sep 14 17:05:30 CEST 2012


New submission from David Beazley:

I've been playing with the interaction of ctypes and memoryviews and am curious about intended behavior.  Consider the following:

>>> import ctypes
>>> d = ctypes.c_double()
>>> m = memoryview(d)
>>> m.ndim
0
>>> m.shape
()
>>> m.readonly
False
>>> m.itemsize
8
>>>

As you can see, you have a memory view for the ctypes double object.  However, the fact that it has a 0-dimension and no shape seems to cause all sorts of weird behavior.  For instance, indexing and slicing don't work:

>>> m[0]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: invalid indexing of 0-dim memory
>>> m[:]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: invalid indexing of 0-dim memory
>>> 

As such, you can't really seem to do anything interesting with the resulting memory view.  For example, you can't pull data out of it.  Nor can you overwrite the contents (i.e., replacing the contents with an 8-byte byte string).

Attempting to cast the memory view to something else doesn't work either.

>>> d = ctypes.c_double()
>>> m = memoryview(d)
>>> m2 = m.cast('c')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: memoryview: source format must be a native single character format prefixed with an optional '@'
>>> 

I must be missing something really obvious here.  Is there no way to get access to the memory behind a ctypes object?

----------
messages: 170477
nosy: dabeaz
priority: normal
severity: normal
status: open
title: memoryviews and ctypes
type: behavior
versions: Python 3.3

_______________________________________
Python tracker <report at bugs.python.org>
<http://bugs.python.org/issue15944>
_______________________________________


More information about the New-bugs-announce mailing list