@@ -527,6 +527,26 @@ def as_array(obj, shape=None):
527
527
528
528
The shape parameter must be given if converting from a ctypes POINTER.
529
529
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
+
530
550
"""
531
551
if isinstance (obj , ctypes ._Pointer ):
532
552
# convert pointers to an array of the desired shape
@@ -541,8 +561,31 @@ def as_array(obj, shape=None):
541
561
542
562
543
563
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
+ """
546
589
ai = obj .__array_interface__
547
590
if ai ["strides" ]:
548
591
raise TypeError ("strided arrays not supported" )
0 commit comments