Skip to content

Commit e9fca94

Browse files
authored
Merge pull request numpy#27598 from m-clare/ctypeslib-examples
2 parents a905925 + ce75474 commit e9fca94

File tree

1 file changed

+45
-2
lines changed

1 file changed

+45
-2
lines changed

numpy/ctypeslib.py

Lines changed: 45 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -527,6 +527,26 @@ def as_array(obj, shape=None):
527527
528528
The shape parameter must be given if converting from a ctypes POINTER.
529529
The shape parameter is ignored if converting from a ctypes array
530+
531+
Examples
532+
--------
533+
Converting a ctypes integer array:
534+
535+
>>> import ctypes
536+
>>> ctypes_array = (ctypes.c_int * 5)(0, 1, 2, 3, 4)
537+
>>> np_array = np.ctypeslib.as_array(ctypes_array)
538+
>>> np_array
539+
array([0, 1, 2, 3, 4], dtype=int32)
540+
541+
Converting a ctypes POINTER:
542+
543+
>>> import ctypes
544+
>>> buffer = (ctypes.c_int * 5)(0, 1, 2, 3, 4)
545+
>>> pointer = ctypes.cast(buffer, ctypes.POINTER(ctypes.c_int))
546+
>>> np_array = np.ctypeslib.as_array(pointer, (5,))
547+
>>> np_array
548+
array([0, 1, 2, 3, 4], dtype=int32)
549+
530550
"""
531551
if isinstance(obj, ctypes._Pointer):
532552
# convert pointers to an array of the desired shape
@@ -541,8 +561,31 @@ def as_array(obj, shape=None):
541561

542562

543563
def as_ctypes(obj):
544-
"""Create and return a ctypes object from a numpy array. Actually
545-
anything that exposes the __array_interface__ is accepted."""
564+
"""
565+
Create and return a ctypes object from a numpy array. Actually
566+
anything that exposes the __array_interface__ is accepted.
567+
568+
Examples
569+
--------
570+
Create ctypes object from inferred int ``np.array``:
571+
572+
>>> inferred_int_array = np.array([1, 2, 3])
573+
>>> c_int_array = np.ctypeslib.as_ctypes(inferred_int_array)
574+
>>> type(c_int_array)
575+
<class 'c_long_Array_3'>
576+
>>> c_int_array[:]
577+
[1, 2, 3]
578+
579+
Create ctypes object from explicit 8 bit unsigned int ``np.array`` :
580+
581+
>>> exp_int_array = np.array([1, 2, 3], dtype=np.uint8)
582+
>>> c_int_array = np.ctypeslib.as_ctypes(exp_int_array)
583+
>>> type(c_int_array)
584+
<class 'c_ubyte_Array_3'>
585+
>>> c_int_array[:]
586+
[1, 2, 3]
587+
588+
"""
546589
ai = obj.__array_interface__
547590
if ai["strides"]:
548591
raise TypeError("strided arrays not supported")

0 commit comments

Comments
 (0)