WARNING

Be careful using the ctypes attribute — especially on temporary arrays or arrays constructed on the fly. For example, calling (a+b).ctypes.data_as(ctypes.c_void_p) returns a pointer to memory that is invalid because the array created as (a+b) is deallocated before the next Python statement. You can avoid this problem using either c=a+b or ct=(a+b).ctypes. In the latter case, ct will hold a reference to the array until ct is deleted or re-assigned.

The ctypes object also has several methods which can alter how the shape, strides, and data of the underlying object is returned.

data_as (obj) Return the data pointer cast-to a particular c-types object. For example, calling sel f. _as_parameter_ is equivalent to self . data_as (ctypes . c_void_p) . Perhaps you want to use the data as a pointer to a ctypes array of floating-point data: self .data.as (ctypes . POINTER (ctypes . c_double) ).

shape_as (obj) Return the shape tuple as an array of some other c-types type. For example: self . shape.as (ctypes . c.short) .

strides^as (obj) Return the strides tuple as an array of some other c-types type. For example: self . strides_as (ctypes . c_longlong) .

If the ctypes module is not available, then the ctypes attribute of array objects still returns something useful, but ctypes objects are not returned and errors may be raised instead. In particular, the object will still have the _as_parameter_ attribute which will return an integer equal to the data attribute.

3.2 ndarray Methods

In NumPy, the ndarray object has many methods which operate on or with the array in some fashion, typically returning an array result. In Numeric, many of these methods were only library calls. These methods are explained in this chapter. Whenever the array whose method is being called needs to be referenced it will be referred to as this array, or self. Keyword arguments will be shown. Methods that only take one argument do not have keyword arguments. Default values for one argument methods will be shown in braces {default}.

0 0

Post a comment