numpy.ma.masked_array.ctypes#

属性

ma.masked_array.ctypes#

一个简化数组与 ctypes 模块交互的对象。

此属性创建一个对象,以便在使用 ctypes 模块调用共享库时更方便地使用数组。返回的对象(除其他外)具有 data、shape 和 strides 属性(参见下面的“注意事项”),这些属性本身会返回 ctypes 对象,可作为参数传递给共享库。

参数:
返回:
cPython 对象

具有 data、shape、strides 等属性。

另请参阅

numpy.ctypeslib

注意事项

以下是此对象中已在“NumPy 指南”中记录的公共属性(我们已省略了未记录的公共属性以及已记录的私有属性)

_ctypes.data

指向数组内存区域的指针,表示为 Python 整数。此内存区域可能包含未对齐或字节序不正确的数据。此内存区域甚至可能不可写入。将此属性传递给任意 C 代码时,应遵守此数组的标志和数据类型,以避免可能导致 Python 崩溃的问题。用户请注意!此属性的值与以下内容完全相同:self._array_interface_['data'][0]

请注意,与 data_as 不同,不会保留对数组的引用:像 ctypes.c_void_p((a + b).ctypes.data) 这样的代码将导致指向已解除分配数组的指针,应写成 (a + b).ctypes.data_as(ctypes.c_void_p)

_ctypes.shape

(c_intp*self.ndim):一个长度为 self.ndim 的 ctypes 数组,其基类型是此平台上对应于 dtype('p') 的 C 整数(参见 c_intp)。此基类型可以是 ctypes.c_intctypes.c_longctypes.c_longlong,具体取决于平台。此 ctypes 数组包含底层数组的形状。

_ctypes.strides

(c_intp*self.ndim):一个长度为 self.ndim 的 ctypes 数组,其基类型与 shape 属性的基类型相同。此 ctypes 数组包含底层数组的步幅信息。此步幅信息对于指示在数组中跳过多少字节才能到达下一个元素至关重要。

_ctypes.data_as(obj)[源]

返回转换为特定 C-type 对象的 data 指针。例如,调用 self._as_parameter_ 等同于 self.data_as(ctypes.c_void_p)。您可能希望将 data 用作指向 ctypes 浮点数据数组的指针:self.data_as(ctypes.POINTER(ctypes.c_double))

返回的指针将保留对数组的引用。

_ctypes.shape_as(obj)[源]

将 shape 元组作为其他 C-type 类型的数组返回。例如:self.shape_as(ctypes.c_short)

_ctypes.strides_as(obj)[源]

将 strides 元组作为其他 C-type 类型的数组返回。例如:self.strides_as(ctypes.c_longlong)

如果 ctypes 模块不可用,则数组对象的 ctypes 属性仍会返回一些有用的内容,但不会返回 ctypes 对象,而可能会引发错误。特别是,该对象仍将具有 as_parameter 属性,该属性将返回一个与 data 属性相等的整数。

示例

>>> import numpy as np
>>> import ctypes
>>> x = np.array([[0, 1], [2, 3]], dtype=np.int32)
>>> x
array([[0, 1],
       [2, 3]], dtype=int32)
>>> x.ctypes.data
31962608 # may vary
>>> x.ctypes.data_as(ctypes.POINTER(ctypes.c_uint32))
<__main__.LP_c_uint object at 0x7ff2fc1fc200> # may vary
>>> x.ctypes.data_as(ctypes.POINTER(ctypes.c_uint32)).contents
c_uint(0)
>>> x.ctypes.data_as(ctypes.POINTER(ctypes.c_uint64)).contents
c_ulong(4294967296)
>>> x.ctypes.shape
<numpy._core._internal.c_long_Array_2 object at 0x7ff2fc1fce60> # may vary
>>> x.ctypes.strides
<numpy._core._internal.c_long_Array_2 object at 0x7ff2fc1ff320> # may vary