[issue11429] ctypes is highly eclectic in its raw-memory support

eryksun report at bugs.python.org
Thu Jul 31 23:46:41 CEST 2014


eryksun added the comment:

Extending byref to support bytes and str objects sounds reasonable. 

Here's another workaround to pass a bytes object with an offset:

    from ctypes import *
    from ctypes.util import find_library

    class offset:
        def __init__(self, arg, offset):
            self.arg = arg
            self.offset = offset

    class my_char_p(c_char_p):
        @classmethod
        def from_param(cls, arg):
            if isinstance(arg, offset):
                t = cast(arg.arg, POINTER(c_char * 0))[0]
                carg = byref(t, arg.offset)
            else:
                carg = super().from_param(arg)
            return carg

    atoi = CDLL(find_library('c')).atoi
    atoi.argtypes = [my_char_p]

    >>> atoi(b'12345')
    12345
    >>> atoi(offset(b'12345', 1))
    2345
    >>> atoi(offset(b'12345', 3))
    45

You can also convert bytearray, memoryview, and array.array objects from_param. If the object's buffer is writable you can use a ctypes type's from_buffer method to create the C arg. This takes an optional offset argument. Otherwise use from_buffer_copy or cast.

----------
nosy: +eryksun

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


More information about the Python-bugs-list mailing list