module documentation

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
Function as​_array Create a numpy array from a ctypes array or POINTER.
Function as​_ctypes Create and return a ctypes object from a numpy array. Actually anything that exposes the __array_interface__ is accepted.
Function as​_ctypes​_type Convert a dtype into a ctypes type.
Function ndpointer Array-checking restype/argtypes.
Variable ctypes Undocumented
Class ​_concrete​_ndptr Like _ndptr, but with _shape_ and _dtype_ specified.
Class ​_ndptr Undocumented
Function ​_ctype​_from​_dtype Undocumented
Function ​_ctype​_from​_dtype​_scalar Undocumented
Function ​_ctype​_from​_dtype​_structured Undocumented
Function ​_ctype​_from​_dtype​_subarray Undocumented
Function ​_ctype​_ndarray Create an ndarray of the given element type and shape
Function ​_dummy Dummy object that raises an ImportError if ctypes is not available.
Function ​_flags​_fromnum Undocumented
Function ​_get​_scalar​_type​_map Return a dictionary mapping native endian scalar dtype to ctypes types
Function ​_num​_fromflags Undocumented
Variable ​_flagnames Undocumented
Variable ​_pointer​_type​_cache Undocumented
Variable ​_scalar​_type​_map Undocumented
def as_array(obj, shape=None):

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

def as_ctypes(obj):
Create and return a ctypes object from a numpy array. Actually anything that exposes the __array_interface__ is accepted.
def as_ctypes_type(dtype):

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.Structures and ctypes.Unions
  • convert single-element ctypes.Unions into single-element ctypes.Structures
  • insert padding fields
def ndpointer(dtype=None, ndim=None, shape=None, flags=None):

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
  • UPDATEIFCOPY / U

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
ctypes =

Undocumented

def _ctype_from_dtype(dtype):

Undocumented

def _ctype_from_dtype_scalar(dtype):

Undocumented

def _ctype_from_dtype_structured(dtype):

Undocumented

def _ctype_from_dtype_subarray(dtype):

Undocumented

def _ctype_ndarray(element_type, shape):
Create an ndarray of the given element type and shape
def _dummy(*args, **kwds):

Dummy object that raises an ImportError if ctypes is not available.

Raises

ImportError
If ctypes is not available.
def _flags_fromnum(num):

Undocumented

def _get_scalar_type_map():
Return a dictionary mapping native endian scalar dtype to ctypes types
def _num_fromflags(flaglist):

Undocumented

_flagnames: list[str] =

Undocumented

_pointer_type_cache: dict =

Undocumented

_scalar_type_map =

Undocumented