zmc
2023-08-08 e792e9a60d958b93aef96050644f369feb25d61b
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
U
O±dWFã@srdZddddddgZddlZdd    lmZmZmZmZm    Z    dd
l
m Z m Z z ddl Z Wnek
rldZ YnXe dkrœd d „ZeZeZeZdd lmZeZn*ddlmmZe ¡Z[e jZdd„Zdd„ZddddddgZdd„ZGdd„deƒZ Gdd„de ƒZ!iZ"d-dd„Z#e dk    rndd„Z$d d!„Z%e%ƒZ&d"d#„Z'd$d%„Z(d&d'„Z)d(d)„Z*d*d„Z+d.d+d„Zd,d„ZdS)/a7
============================
``ctypes`` Utility Functions
============================
 
See Also
--------
load_library : Load a C library.
ndpointer : Array restype/argtype with verification.
as_ctypes : Create a ctypes array from an ndarray.
as_array : Create an ndarray from a ctypes array.
 
References
----------
.. [1] "SciPy Cookbook: ctypes", https://scipy-cookbook.readthedocs.io/items/Ctypes.html
 
Examples
--------
Load the C library:
 
>>> _lib = np.ctypeslib.load_library('libmystuff', '.')     #doctest: +SKIP
 
Our result type, an ndarray that must be of type double, be 1-dimensional
and is C-contiguous in memory:
 
>>> array_1d_double = np.ctypeslib.ndpointer(
...                          dtype=np.double,
...                          ndim=1, flags='CONTIGUOUS')    #doctest: +SKIP
 
Our C-function typically takes an array and updates its values
in-place.  For example::
 
    void foo_func(double* x, int length)
    {
        int i;
        for (i = 0; i < length; i++) {
            x[i] = i*i;
        }
    }
 
We wrap it using:
 
>>> _lib.foo_func.restype = None                      #doctest: +SKIP
>>> _lib.foo_func.argtypes = [array_1d_double, c_int] #doctest: +SKIP
 
Then, we're ready to call ``foo_func``:
 
>>> out = np.empty(15, dtype=np.double)
>>> _lib.foo_func(out, len(out))                #doctest: +SKIP
 
Ú load_libraryÚ    ndpointerÚc_intpÚ    as_ctypesÚas_arrayÚas_ctypes_typeéN)ÚintegerÚndarrayÚdtypeÚasarrayÚ
frombuffer)Ú    _flagdictÚflagsobjcOs tdƒ‚dS)z±
        Dummy object that raises an ImportError if ctypes is not available.
 
        Raises
        ------
        ImportError
            If ctypes is not available.
 
        zctypes is not available.N)Ú ImportError)ÚargsÚkwds©rúFd:\z\workplace\vscode\pyvenv\venv\Lib\site-packages\numpy/ctypeslib.pyÚ_dummyCs
r)Úintpc     Cstjdkr ddl}|jdddt |¡}t |¡}tj |¡d}|sˆddlm    }|ƒ}||g}|d    d
}||ksŽ| 
d||¡n|g}tj  |¡}tj  |¡s´tj  |¡}n|}|D]H}    tj ||    ¡}
tj |
¡r¼ztj|
WStk
r‚Yq¼Xq¼td ƒ‚dS) a
 
        It is possible to load a library using
 
        >>> lib = ctypes.cdll[<full_path_name>] # doctest: +SKIP
 
        But there are cross-platform considerations, such as library file extensions,
        plus the fact Windows will just load the first library it finds with that name.
        NumPy supplies the load_library function as a convenience.
 
        .. versionchanged:: 1.20.0
            Allow libname and loader_path to take any
            :term:`python:path-like object`.
 
        Parameters
        ----------
        libname : path-like
            Name of the library, which can have 'lib' as a prefix,
            but without an extension.
        loader_path : path-like
            Where the library can be found.
 
        Returns
        -------
        ctypes.cdll[libpath] : library object
           A ctypes library object
 
        Raises
        ------
        OSError
            If there is no library with the expected extension, or the
            library is defective and cannot be loaded.
        z1.0.1rNzAAll features of ctypes interface may not work with ctypes < 1.0.1é)Ú
stacklevelé)Úget_shared_lib_extensionT)Z is_python_extzno file with expected extension)ÚctypesÚ __version__ÚwarningsÚwarnÚosÚfsdecodeÚpathÚsplitextZnumpy.distutils.misc_utilrÚinsertÚabspathÚisdirÚdirnameÚjoinÚexistsÚcdllÚOSError) ÚlibnameZ loader_pathrÚextrZso_extZ libname_extZso_ext2ZlibdirÚlnZlibpathrrrrZs8!
ÿ
 
 
 
 
cCsd}|D]}|t|7}q|S©Nr)r )ZflaglistÚnumÚvalrrrÚ_num_fromflags¦sr0Z C_CONTIGUOUSZ F_CONTIGUOUSZALIGNEDZ    WRITEABLEZOWNDATAZWRITEBACKIFCOPYcCs,g}tD]}t|}||@r| |¡q|S©N)Ú
_flagnamesr Úappend)r.ÚresÚkeyÚvaluerrrÚ_flags_fromnum®s  r7c@seZdZedd„ƒZdS)Ú_ndptrcCs¸t|tƒstdƒ‚|jdk    r6|j|jkr6td|jƒ‚|jdk    rZ|j|jkrZtd|jƒ‚|jdk    r‚|j|jkr‚tdt    |jƒƒ‚|j
dk    r²|j j |j
@|j
kr²tdt |j
ƒƒ‚|jS)Nzargument must be an ndarrayzarray must have data type %szarray must have %d dimension(s)zarray must have shape %szarray must have flags %s)Ú
isinstancer    Ú    TypeErrorÚ_dtype_r
Ú_ndim_ÚndimÚ_shape_ÚshapeÚstrÚ_flags_Úflagsr.r7r)ÚclsÚobjrrrÚ
from_param¸s*
 
 
ÿ
 
ÿ
 
ÿ
ÿÿz_ndptr.from_paramN)Ú__name__Ú
__module__Ú __qualname__Ú classmethodrErrrrr8·sr8c@s$eZdZdZdd„Zedd„ƒZdS)Ú_concrete_ndptrz¹
    Like _ndptr, but with `_shape_` and `_dtype_` specified.
 
    Notably, this means the pointer has enough information to reconstruct
    the array, which is not generally true.
    cCs|jS)z¹
        This method is called when this class is used as the .restype
        attribute for a shared-library function, to automatically wrap the
        pointer into an array.
        )Úcontents)ÚselfrrrÚ_check_retval_Ósz_concrete_ndptr._check_retval_cCsDt|j|jfƒ}tj|j}t |t |¡¡j}t    ||dj
ddS)z—
        Get an ndarray viewing the data pointed to by this pointer.
 
        This mirrors the `contents` attribute of a normal ctypes pointer
        ©r
r)Zaxis) Ú_dtyper;r>rÚc_charÚitemsizeÚcastÚPOINTERrKr Zsqueeze)rLZ
full_dtypeZ
full_ctypeÚbufferrrrrKÛs z_concrete_ndptr.contentsN)rFrGrHÚ__doc__rMÚpropertyrKrrrrrJÌsrJc
 
Csâ|dk    rt|ƒ}d}|dk    r¶t|tƒr2| d¡}n4t|ttfƒrN|}t|ƒ}nt|tƒrf|j}t|ƒ}|dkr¶zdd„|Dƒ}Wn,t    k
r¬}zt
dƒ|‚W5d}~XYnXt |ƒ}|dk    ræz t |ƒ}Wnt
k
rä|f}YnX||||f}z
t |WStk
rYnX|dkr$d}n |jdk    r>tt|ƒƒ}n|j}|dk    rZ|d|7}|dk    r€|dd     d
d „|Dƒ¡7}|dk    rœ|dd |¡7}|dk    r¶|dk    r¶t}nt}td ||f||||d œƒ}    |    t |<|    S)aF
    Array-checking restype/argtypes.
 
    An ndpointer instance is used to describe an ndarray in restypes
    and argtypes specifications.  This approach is more flexible than
    using, for example, ``POINTER(c_double)``, since several restrictions
    can be specified, which are verified upon calling the ctypes function.
    These include data type, number of dimensions, shape and flags.  If a
    given array does not satisfy the specified restrictions,
    a ``TypeError`` is raised.
 
    Parameters
    ----------
    dtype : data-type, optional
        Array data-type.
    ndim : int, optional
        Number of array dimensions.
    shape : tuple of ints, optional
        Array shape.
    flags : str or tuple of str
        Array flags; may be one or more of:
 
          - C_CONTIGUOUS / C / CONTIGUOUS
          - F_CONTIGUOUS / F / FORTRAN
          - OWNDATA / O
          - WRITEABLE / W
          - ALIGNED / A
          - WRITEBACKIFCOPY / X
 
    Returns
    -------
    klass : ndpointer type object
        A type object, which is an ``_ndtpr`` instance containing
        dtype, ndim, shape and flags information.
 
    Raises
    ------
    TypeError
        If a given array does not satisfy the specified restrictions.
 
    Examples
    --------
    >>> clib.somefunc.argtypes = [np.ctypeslib.ndpointer(dtype=np.float64,
    ...                                                  ndim=1,
    ...                                                  flags='C_CONTIGUOUS')]
    ... #doctest: +SKIP
    >>> clib.somefunc(np.array([1, 2, 3], dtype=np.float64))
    ... #doctest: +SKIP
 
    Nú,cSsg|]}| ¡ ¡‘qSr)ÚstripÚupper©Ú.0ÚxrrrÚ
<listcomp>0szndpointer.<locals>.<listcomp>zinvalid flags specificationÚanyz_%ddÚ_r\css|]}t|ƒVqdSr1)r@rZrrrÚ    <genexpr>Nszndpointer.<locals>.<genexpr>z ndpointer_%s)r;r>r<rA)rOr9r@ÚsplitÚintrr7rr.Ú    Exceptionr:r0ÚtupleÚ_pointer_type_cacheÚKeyErrorÚnamesÚidr&rJr8Útype)
r
r=r?rBr.ÚeÚ    cache_keyÚnameÚbaseÚklassrrrrësf5
 
 
 
 
 
 
 
 ýÿcCs&|ddd…D]}||}d|_q|S)z7 Create an ndarray of the given element type and shape Néÿÿÿÿ)rG)Z element_typer?ZdimrrrÚ_ctype_ndarrayasrpc CsJt}|j|j|j|j|j|j|j|j|j    |j
|j |j |j g }dd„|DƒS)zX
        Return a dictionary mapping native endian scalar dtype to ctypes types
        cSsi|]}t|ƒ|“qSr)rO)r[ÚctyperrrÚ
<dictcomp>usz(_get_scalar_type_map.<locals>.<dictcomp>)rÚc_byteÚc_shortÚc_intÚc_longÚ
c_longlongÚc_ubyteÚc_ushortÚc_uintÚc_ulongÚ c_ulonglongÚc_floatÚc_doubleÚc_bool)ÚctZ simple_typesrrrÚ_get_scalar_type_mapjs ürc
Cs€| d¡ d¡}| d¡}z t|}Wn2tk
rX}ztd |¡ƒd‚W5d}~XYnX|jdkrl|j}n|jdkr||j}|S)NÚSú=z Converting {!r} to a ctypes typeú>ú<)Z newbyteorderÚ_scalar_type_maprfÚNotImplementedErrorÚformatÚ    byteorderÚ __ctype_be__Ú __ctype_le__)r
Zdtype_with_endianZ dtype_nativerqrjrrrÚ_ctype_from_dtype_scalar{s
 ÿþ
 
rŒcCs|j\}}t|ƒ}t||ƒSr1)ÚsubdtypeÚ_ctype_from_dtyperp)r
Z element_dtyper?rqrrrÚ_ctype_from_dtype_subarrayŽs
rc
CsŠg}|jD].}|j|dd…\}}| ||t|ƒf¡q
t|dd„d}t|ƒdkrØtdd„|DƒƒrØd}g}|D](\}}}| ||f¡t|t     |¡ƒ}qt|j
|kr¾| d    tj |j
f¡t d
tj ft|ddd ƒSd}g}|D]^\}}}||}    |    dkrtd ƒ‚|    dkr&| d    tj |    f¡| ||f¡|t     |¡}qä|j
|}    |    dkrl| d    tj |    f¡t d tjft|ddd ƒSdS)NrcSs|dSr-r)ÚfrrrÚ<lambda>œóz._ctype_from_dtype_structured.<locals>.<lambda>)r5rcss|]\}}}|dkVqdS)rNr)r[Úoffsetrlrqrrrr`žsz/_ctype_from_dtype_structured.<locals>.<genexpr>rÚÚunion)Ú_fields_Ú_pack_rGzOverlapping fieldsÚstruct)rgÚfieldsr3rŽÚsortedÚlenÚallÚmaxrÚsizeofrQrPriÚUnionÚdictr‡Ú    Structure)
r
Z
field_datarlZ field_dtyper“Úsizer–rqZ last_offsetÚpaddingrrrÚ_ctype_from_dtype_structured”sH
 
 ý
 
 
 
 ýr¤cCs0|jdk    rt|ƒS|jdk    r$t|ƒSt|ƒSdSr1)r™r¤rrrŒrNrrrrŽÊs
 
 
rŽcCs tt|ƒƒS)a…
        Convert a dtype into a ctypes type.
 
        Parameters
        ----------
        dtype : dtype
            The dtype to convert
 
        Returns
        -------
        ctype
            A ctype scalar, union, array, or struct
 
        Raises
        ------
        NotImplementedError
            If the conversion is not possible
 
        Notes
        -----
        This function does not losslessly round-trip in either direction.
 
        ``np.dtype(as_ctypes_type(dt))`` will:
 
         - insert padding fields
         - reorder fields to be sorted by offset
         - discard field titles
 
        ``as_ctypes_type(np.dtype(ctype))`` will:
 
         - discard the class names of `ctypes.Structure`\ s and
           `ctypes.Union`\ s
         - convert single-element `ctypes.Union`\ s into single-element
           `ctypes.Structure`\ s
         - insert padding fields
 
        )rŽrOrNrrrrÓs&cCsDt|tjƒr<|dkrtdƒ‚t t|j|ƒ¡}t ||¡j}t    |ƒS)a"
        Create a numpy array from a ctypes array or POINTER.
 
        The numpy array shares the memory with the ctypes object.
 
        The shape parameter must be given if converting from a ctypes POINTER.
        The shape parameter is ignored if converting from a ctypes array
        Nz=as_array() requires a shape argument when called on a pointer)
r9rÚ_Pointerr:rSrpÚ_type_rRrKr )rDr?Z
p_arr_typerrrrüs     ÿcCsp|j}|drtdƒ‚|ddkr*tdƒ‚|d\}}|rBtdƒ‚t|dƒ}t||d    ƒ}| |¡}||_|S)
z‚Create and return a ctypes object from a numpy array.  Actually
        anything that exposes the __array_interface__ is accepted.Ústrideszstrided arrays not supportedÚversionéz,only __array_interface__ version 3 supportedÚdatazreadonly arrays unsupportedZtypestrr?)Z__array_interface__r:rrpÚ from_addressZ__keep)rDZaiÚaddrÚreadonlyZ ctype_scalarZ result_typeÚresultrrrrs   
)NNNN)N),rUÚ__all__rÚnumpyrr    r
rOr r Znumpy.core.multiarrayr rrrrrrrrrÚobjectZ _ndptr_baseZnumpy.core._internalÚcoreÚ    _internalZnicZ_getintp_ctypeÚc_void_pr0r2r7r8rJrerrprr†rŒrr¤rŽrrrrrÚ<module>sV3
ÿ 
  Lÿ    
u
    6    )