How to write partial of a buffer which was returned from a C function to a file?

eryk sun eryksun at gmail.com
Fri Apr 13 17:27:34 EDT 2018


On Fri, Apr 13, 2018 at 8:44 AM, Jach Fong <jfong at ms4.hinet.net> wrote:
>
> After studying the example you explained in your previous post replied to
> Gregory Ewing, I had noticed that until today I was totally misunderstand
> the meaning of the c_char_p. I always think it "is" a pointer, but actually
> it's just a ctypes type, maybe literarily looks like a C pointer, but not a
> pointer from the ctypes view at all:-)

Here's a list of type classes in ctypes:

    class             metaclass
    =================================
    _SimpleCData      PyCSimpleType
    _Pointer          PyCPointerType
    _CFuncPtr         PyCFuncPtrType
    Array             PyCArrayType
    Structure         PyCStructType
    Union             UnionType

These classes share a common _CData base class. Note that the _ctypes
extension module doesn't directly expose _CData, nor any of the
metaclasses.

ctypes type checking primarily uses Python type checking, so we
generally do not subclass these types directly, except for Structure
and Union. Instead we have a set of predefined simple types that
subclass _SimpleCData (e.g. c_int, c_char), and we use factory
functions to create pointer types (e.g. POINTER, CFUNCTYPE), which
cache the created type. For arrays, we rely on the base _CData
sequence-repeat functionality (e.g. c_int * 3), which also caches the
Array subclass that it creates.

Type caching ensures that two expressions that create an equivalent C
type return the same class. For example, if you have `c_char * 3` in
two places, it should be the same type:

    >>> cls = ctypes.c_char * 3
    >>> (ctypes.c_char * 3) is cls
    True

The simple types c_void_p, c_char_p, and c_wchar_p are pointers.
However, since they subclass _SimpleCData instead of _Pointer, they
inherit the behavior of simple types. In particular they have get/set
functions that implicitly convert to and from native Python types when
they're used in aggregate types (arrays, structs, unions), when
indexing or slicing a _Pointer instance, or as the result or argument
of a function pointer (i.e. _CFuncPtr subclass).


More information about the Python-list mailing list