Next topic

This Page

Quick search

Interfacing with some native libraries (for example written in C or C++)
can necessitate writing native callbacks to provide business logic to the
library. The numba.cfunc() decorator creates a compiled function
callable from foreign C code, using the signature of your choice.

The C function object exposes the address of the compiled C callback as
the address attribute, so that you can pass it to any
foreign C or C++ library. It also exposes a ctypes callback
object pointing to that callback; that object is also callable from
Python, making it easy to check the compiled code:

A less trivial use case of C callbacks involves doing operation on some
array of data passed by the caller. As C doesn’t have a high-level
abstraction similar to Numpy arrays, the C callback’s signature will pass
low-level pointer and size arguments. Nevertheless, the Python code for
the callback will expect to exploit the power and expressiveness of Numpy
arrays.

In the following example, the C callback is expected to operate on 2-d arrays,
with the signature void(double*input,double*output,intm,intn).
You can implement such a callback thusly:

The numba.carray() function takes as input a data pointer and a shape
and returns an array view of the given shape over that data. The data is
assumed to be laid out in C order. If the data is laid out in Fortran order,
numba.farray() should be used instead.

The explicit @cfunc signature can use any Numba types,
but only a subset of them make sense for a C callback. You should
generally limit yourself to scalar types (such as int8 or float64)
or pointers to them (for example types.CPointer(types.int8)).