w~FdZgdZddlZddlmZmZmZmZm Z ddl m Z m Z  ddl Z n #e$rdZ YnwxYwe dZeZeZeZddlmZeZn#ddlmcmZejZ[e jZdZd Zgd Zd ZGd d eZ Gdde Z!iZ"ddZ#e (dZ$dZ%e%Z&dZ'dZ(dZ)dZ*dZ+ddZdZdSdS)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 ndpointerc_intp as_ctypesas_arrayas_ctypes_typeN)integerndarraydtypeasarray frombuffer) _flagdictflagsobjc td)z Dummy object that raises an ImportError if ctypes is not available. Raises ------ ImportError If ctypes is not available. zctypes is not available.) ImportError)argskwdss c/builddir/build/BUILD/cloudlinux-venv-1.0.10/venv/lib64/python3.11/site-packages/numpy/ctypeslib.py_dummyrCs4555)intpcPtj|}tj|}tj|d}|s~ddl}ddl}d}|jdrd}n|jdrd}||zg}|d }||ks| d||zn|g}tj |}tj |s tj |}n|}|D]e} tj || } tj| r$ tj| cS#t"$rwxYwft#d ) a  It is possible to load a library using >>> lib = ctypes.cdll[] # 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. rNz.sodarwinz.dylibwinz.dll EXT_SUFFIXzno file with expected extension)osfsdecodepathsplitextsys sysconfigplatform startswithget_config_varinsertabspathisdirdirnamejoinexistsctypescdllOSError) libname loader_pathextr!r"base_ext libname_extso_extlibdirlnlibpaths rrrZsD+g&&k+.. gw''* $ JJJ    H|&&x00 "#((// "!"X-.K--l;;FX%%""1g&6777")Kgook22 w}}[)) !W__[11FF F  Bgll62..Gw~~g&& !;w//// 7888s 5F  Fc4d}|D]}|t|z }|SNr)r)flaglistnumvals r_num_fromflagsr=s+ C y~ Jr) C_CONTIGUOUS F_CONTIGUOUSALIGNED WRITEABLEOWNDATAWRITEBACKIFCOPYclg}tD])}t|}||zr||*|SN) _flagnamesrappend)r;reskeyvalues r_flags_fromnumrKs@ C# %K  JJsOOO Jrc$eZdZedZdS)_ndptrct|tstd|j'|j|jkrtd|jz|j'|j|jkrtd|jz|j4|j|jkr$tdt|jz|j A|j j |j z|j kr$tdt|j z|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_shapestr_flags_flagsr;rKr,)clsobjs r from_paramz_ndptr.from_params#w'' ;9:: : ; "9 ++:S[HII I : !8sz))= JKK K ; "9 ++6S[9I9IIJJ J ; "Y]S[0S[@@6"3;//011 1zrN)__name__ __module__ __qualname__ classmethodr[rrrMrMs-[rrMc.eZdZdZdZedZdS)_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. c|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)selfs r_check_retval_z_concrete_ndptr._check_retval_s }rct|j|jf}tj|jz}tj|tj|j}t|| dS)z Get an ndarray viewing the data pointed to by this pointer. This mirrors the `contents` attribute of a normal ctypes pointer r r)axis) _dtyperQrTr,c_charitemsizecastPOINTERrdr squeeze)re full_dtype full_ctypebuffers rrdz_concrete_ndptr.contentsskT\4<899 ]Z%88 T6>*#=#=>>G& 333;;;CCCrN)r\r]r^__doc__rfpropertyrdr`rrrbrbsM  D DX D D Drrbc |t|}d}|t|tr|d}nYt|tt fr|}t |}n+t|tr|j}t |}|? d|D}n"#t$r}td|d}~wwxYwt|}|$ t|}n#t$r|f}YnwxYw||||f} t|S#t$rYnwxYw|d}n+|jtt!|}n|j}||d|zz }|%|ddd |Dzz }||dd|zz }| |t$}nt&}t)d |z|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,cZg|](}|)Sr`)stripupper.0xs r zndpointer...s*:::q**:::rzinvalid flags specificationanyz_%dd_r|c34K|]}t|VdSrE)rVrzs r zndpointer..Ls(33SVV333333rz ndpointer_%s)rQrTrRrW)rjrOrVsplitintr rKrr; ExceptionrPr=tuple_pointer_type_cacheKeyErrornamesidr*rbrMtype) r rSrUrXr;e cache_keynamebaseklasss rrrsej u  C  eS ! ! (KK$$EE W~ . . (C"3''EE x ( ( ()C"3''E ; F::E::: F F F =>>AE F ''C  %LLEE   HEEE eS)I "9--       }  2e99~~y     CHH33U3333333  CHHUOO## U. $tg"#!!## $ $E &+ " Ls< B** C 4CC C.. C>=C> D D"!D"c:|dddD]}||z}d|_|S)z7 Create an ndarray of the given element type and shape N)r]) element_typerUdims r_ctype_ndarrayr_s62; + +C-L&*L # #rc t}|j|j|j|j|j|j|j|j|j |j |j |j |j g }d|DS)zX Return a dictionary mapping native endian scalar dtype to ctypes types c.i|]}t||Sr`)rj)r{ctypes r z(_get_scalar_type_map..ss ???u u???r)r,c_bytec_shortc_intc_long c_longlongc_ubytec_ushortc_uintc_ulong c_ulonglongc_floatc_doublec_bool)ct simple_typess r_get_scalar_type_maprhs_ Irz28RY J RY BN J I  @?,????rcR|dd}|d} t|}n5#t$r(}td|dd}~wwxYw|jdkr|j}n|jdkr|j}|S)NS=z Converting {!r} to a ctypes type><) newbyteorder_scalar_type_maprNotImplementedErrorformat byteorder __ctype_be__ __ctype_le__)r dtype_with_endian dtype_nativerrs r_ctype_from_dtype_scalarrys!..s33@@EE))#..  $\2EE   %299%@@    &# - -&EE  (C / /&E s A A?#A::A?cT|j\}}t|}t||SrE)subdtype_ctype_from_dtyper)r element_dtyperUrs r_ctype_from_dtype_subarrayrs+$~ u!-00eU+++rc g}|jD]?}|j|dd\}}|||t|f@t |d}t |dkrt d|Drd}g}|D]?\}}}|||ft|tj |}@|j |kr)|dtj |j zftdtj ft|dd Sd}g}|D]x\}}}||z } | dkrtd | dkr$|dtj | zf|||f|tj |z}y|j |z } | dkr$|dtj | zftd tjft|dd S) Nc|dSr9r`)fs rz._ctype_from_dtype_structured..s adr)rIrc3*K|]\}}}|dkVdS)rNr`)r{offsetrrs rrz/_ctype_from_dtype_structured..s-&Y&Y7JvtUv{&Y&Y&Y&Y&Y&Yrrunion)_fields__pack_r]zOverlapping fieldsstruct)rfieldsrGrsortedlenallmaxr,sizeofrlrkrUniondictr Structure) r field_datar field_dtypersizerr last_offsetpaddings r_ctype_from_dtype_structuredrsX K N ND"',t"4RaR"8 K   vt->{-K-KL M M M MJNN;;; z??Q  3&Y&Yj&Y&Y&Y#Y#Y DH'1 7 7#eu ...4u!5!566~%%V]U^%C DEEE&,$!333  KH'1 < <#e ;.Q;;-.BCCCQ;;OOR)@$ABBBu ...$v}U';';; n{2G{{V]W%< =>>>6#3"5t!888 rcx|jt|S|jt|St |SrE)rrrrrrhs rrrs< < #/66 6 ^ '-e44 4+E22 2rc: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 )rrjrhs rrrsL!///rct|tjrR|tdtjt |j|}tj||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) rOr,_PointerrPrnr_type_rmrdr )rZrU p_arr_types rrrsq c6? + + 8} sz5(I(IJJJ+c:..7Cs||rc>|j}|drtd|ddkrtd|d\}}|rtdt|d}t||d }||}||_|S) zCreate and return a ctypes object from a numpy array. Actually anything that exposes the __array_interface__ is accepted.strideszstrided arrays not supportedversionz,only __array_interface__ version 3 supporteddatazreadonly arrays unsupportedtypestrrU)__array_interface__rPrr from_address__keep)rZaiaddrreadonly ctype_scalar result_typeresults rrrs $ i= <:;; ; i=A  JKK KFh  ;9:: :&bm44 $\2g;?? ))$//  r)NNNNrE),rs__all__rnumpyr r r rjr r numpy.core.multiarrayrrr,rrrrrrrobject _ndptr_basenumpy.core._internalcore _internalnic_getintp_ctypec_void_pr=rFrKrMrbrrrrrrrrrrr`rrrs22f    65555555MMMM FFF > 6 6 6LIH$$$$$$KK&&&&&&&&& S  ! !F /KG9G9G9T ,,, [*DDDDDfDDD<rrrrj  @ @ @,+--&,,, 333l333&0&0&0R*cs '11