Re: Data_as

eryksun <[email protected]> Tue, 30 Dec 2014 18:24:06 -0600
Newsgroups gmane.comp.python.ctypes
Message-ID <CACL+1avuWYft7k=60XPs=VqUAOmLyF4hcUF_mLXbr4msmsRgHw@mail.gmail.com>
On Tue, Dec 30, 2014 at 11:15 AM, West, Peter <[email protected]> wrote:
>
>    pointerArrayType = POINTER( c_uint16 ) * 2      # an array of pointers type length 2
>    pointers = pointerArrayType()                           # the actual array
....
>    print pointers[ 0 ]
>    print pointers[ 1 ]
>
> This prints
> <__main__.LP_c_ushort object at 0x00000000025132C8>
> <__main__.LP_c_ushort object at 0x00000000025132C8>
>
> This suggests that the data arrays for frame1 and frame2 are at the same location.

The repr shows the address of the Python object, not the pointer value.

    >>> x, y = pointers
    >>> print x
    <__main__.LP_c_ushort object at 0x7f10648378c0>
    >>> print y
    <__main__.LP_c_ushort object at 0x7f1064837c20>

The pointer's contents attribute returns a ctypes object that can be
passed to addressof.

    >>> from ctypes import addressof
    >>> pointers[0].contents
    c_ushort(0)
    >>> addressof(pointers[0].contents)
    43254640
    >>> addressof(pointers[1].contents)
    43274656

Note that pointers[0][0] wouldn't work. That converts the c_ushort to
a Python integer.

    >>> pointers[0][0]
    0
    >>> addressof(pointers[0][0])
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    TypeError: invalid type

You could also cast to a void pointer.

    >>> from ctypes import cast, c_void_p
    >>> cast(pointers[0], c_void_p)
    c_void_p(43254640)
    >>> cast(pointers[1], c_void_p)
    c_void_p(43274656)

Or use the buffer protocol instead of cast.

    >>> c_void_p.from_buffer(pointers[0])
    c_void_p(43254640)
    >>> c_void_p.from_buffer(pointers[1])
    c_void_p(43274656)

Verify against the numpy array's ctypes attribute.

    >>> frame1.ctypes.data
    43254640
    >>> frame2.ctypes.data
    43274656

    >>> frame1.ctypes._as_parameter_
    c_void_p(43254640)
    >>> frame2.ctypes._as_parameter_
    c_void_p(43274656)

------------------------------------------------------------------------------
Dive into the World of Parallel Programming! The Go Parallel Website,
sponsored by Intel and developed in partnership with Slashdot Media, is your
hub for all things parallel software development, from weekly thought
leadership blogs to news, videos, case studies, tutorials and more. Take a
look and join the conversation now. http://goparallel.sourceforge.net