C-API, Cython and F2PY

This content was generated with the assistance of AI and should be verified against the official documentation before being relied on in production.

This page was written in October 2026 for NumPy 2.5 (2.5.4 was the current release). Examples target Python 3.13 or 3.14 and were run on Python 3.13. It is an overview: it shows what each route looks like, what each costs, and where the NumPy 2 changes bite. It does not teach C, Cython or Fortran. The C extension, ctypes and Cython examples were built and run on Python 3.13 with NumPy 2.5.4 and Cython 3.3.0. The F2PY examples were not compiled, because no Fortran compiler was available on the machine used, so their commands and output are taken from the official F2PY documentation.

Most readers never need this page: vectorised NumPy, a library that already wraps your routine (SciPy, scikit-learn) or a just-in-time compiler is enough. It matters when a loop cannot be vectorised, when you must call an existing C or Fortran library, or when you maintain a package that links against NumPy and must survive the NumPy 2 ABI change. For the Python-level performance options, see Threads, Free-Threading and Performance. For the NumPy 2 changes that affect extension code, see Migrating to NumPy 2.x.

Choosing a route

The "Using Python as glue" chapter of the NumPy manual compares the main approaches. The comparison below follows it and adds what changed in NumPy 2. The chapter itself is marked as an old text, so its recommendations should be read as a map and not as current tool advice.

Route You write Strengths Costs and risks

C extension with the NumPy C-API

C code with PyArg_ParseTuple and the array macros

Full control, minimal overhead, can release the GIL

You maintain C code and reference counts; ABI rules apply

Cython

A .pyx file: Python with optional static types

Fast to write, typed memoryviews, widely used in SciPy and scikit-learn

Needs a C compiler at build time; generated C is hard to read

ctypes (with numpy.ctypeslib.ndpointer)

Pure Python calling an existing shared library

Standard library, no build step for your own code, reuses existing libraries

Almost no checking beyond what you declare; wrong types crash the interpreter

F2PY

Fortran 77/90/95 source, optionally a signature file or CF2PY comments

Parses Fortran and generates the wrapper automatically

Needs a Fortran compiler; since NumPy 2.5 built with Meson

The chapter also lists SWIG, SIP, Boost.Python and PyFort as older alternatives. They are not covered here.

flowchart TD A[Slow loop or existing compiled code] --> B{Can the loop be vectorised?} B -- yes --> V[Use NumPy ufuncs, see the threading page] B -- no --> C{Is the code already in a shared library?} C -- yes --> D[ctypes with ndpointer, or a C extension] C -- no --> E{Is it Fortran?} E -- yes --> F[F2PY] E -- no --> G[Cython, or a C extension]
Figure 1. Which route to use

The NumPy C-API in a minimal extension

A C extension that uses NumPy arrays follows the usual Python extension layout and adds three NumPy-specific steps:

  1. Define NPY_NO_DEPRECATED_API before including the NumPy headers, so deprecated names fail to compile instead of lingering.

  2. Include numpy/arrayobject.h (or numpy/ndarrayobject.h).

  3. Call import_array() in the module’s init function. It fills NumPy’s function table, and without it any NumPy API call crashes at run time.

The extension below exposes total(arr), which converts its argument to a contiguous double array, checks that it is 1-D, and sums it with the GIL released.

#define PY_SSIZE_T_CLEAN
#include <Python.h>
#define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION
#include <numpy/arrayobject.h>

static PyObject *total(PyObject *self, PyObject *args) {
    PyObject *obj;
    if (!PyArg_ParseTuple(args, "O", &obj)) {
        return NULL;
    }
    PyArrayObject *arr = (PyArrayObject *)PyArray_FROM_OTF(
        obj, NPY_DOUBLE, NPY_ARRAY_IN_ARRAY);
    if (arr == NULL) {
        return NULL;
    }
    if (PyArray_NDIM(arr) != 1) {
        Py_DECREF(arr);
        PyErr_SetString(PyExc_ValueError, "expected a 1-D array");
        return NULL;
    }
    const double *data = (const double *)PyArray_DATA(arr);
    npy_intp n = PyArray_DIM(arr, 0);
    double s = 0.0;
    Py_BEGIN_ALLOW_THREADS
    for (npy_intp i = 0; i < n; ++i) {
        s += data[i];
    }
    Py_END_ALLOW_THREADS
    Py_DECREF(arr);
    return PyFloat_FromDouble(s);
}

static PyMethodDef methods[] = {
    {"total", total, METH_VARARGS, "Sum a 1-D array of doubles."},
    {NULL, NULL, 0, NULL}
};

static struct PyModuleDef moduledef = {
    PyModuleDef_HEAD_INIT, "csum", NULL, -1, methods
};

PyMODINIT_FUNC PyInit_csum(void) {
    import_array();
    return PyModule_Create(&moduledef);
}

PyArray_FROM_OTF with NPY_ARRAY_IN_ARRAY returns a new reference to an array that is C-contiguous, aligned and of the requested type, copying only when needed. That reference must be released with Py_DECREF, including on the error path. Releasing the GIL around the loop lets other Python threads run, which is only valid because the loop touches no Python object.

A setup.py that finds the headers with numpy.get_include() builds it:

from setuptools import Extension, setup
import numpy as np

setup(name="csum", ext_modules=[
    Extension("csum", ["csum.c"], include_dirs=[np.get_include()])])
python setup.py build_ext --inplace
python -c "import numpy as np, csum; print(csum.total(np.arange(5)), csum.total([1, 2, 3.5]))"

Output:

10.0 6.5

A 2-D argument raises ValueError: expected a 1-D array, as coded.

The NumPy manual’s "How to extend NumPy" chapter walks through the same pieces (module initialisation, argument parsing, reference counting, creating and accessing arrays) and the "Writing your own ufunc" chapter shows how to expose a C loop as a real ufunc with broadcasting and out= support. "Beyond the basics" covers iterating over arrays with NpyIter, user-defined dtypes and subclassing ndarray in C.

Finding headers and libraries

numpy.get_include() returns the include directory. Since NumPy 2.3 the package also registers its pkg-config path with the pkgconf package from PyPI when that is installed, and the numpy-config command prints the compile flags (for example numpy-config --cflags) either way. Build systems such as Meson (through meson-python) and CMake can use these instead of calling Python.

The NumPy 2 ABI: building and supporting both 1.x and 2.x

NumPy 2.0 changed the binary interface. The rules from the "Depending on NumPy" guide are:

  • The ABI is forward compatible but not backward compatible: binaries built against an older NumPy work with newer NumPy, but not the other way around. The NumPy 2 ABI has been stable since 2.0.0rc1.

  • A wheel built against NumPy 2.x works with both NumPy 1.x and 2.x. A wheel built against NumPy 1.x does not work with NumPy 2.0 or later.

  • NPY_TARGET_VERSION controls which NumPy C-API your code can rely on. By default NumPy exposes an API compatible with the earliest NumPy release that supports the oldest Python NumPy currently supports. Define it before any NumPy include, or pass -DNPY_TARGET_VERSION=..., if you need newer API at the cost of compatibility with older versions. The value must be the same for every extension module that calls import_array().

  • Modules built against NumPy 2.0 or later can also use CPython’s abi3 mode, which reduces the number of wheels to build.

The consequence for packaging is a split between the build-time and run-time requirements. The example from the guide, for a package that supports NumPy 1.23.5 and later at run time:

[build-system]
requires = [
    "setuptools",
    "numpy>=2.0.0",
]
build-backend = "setuptools.build_meta"

[project]
name = "csum"
version = "0.1"
dependencies = [
    "numpy>=1.23.5",
]

If you only support NumPy 2, use numpy>=2.0 in both places. For releases before 1.25 the oldest-supported-numpy helper package was the recommended way to pick a build version; it is no longer needed now that NPY_TARGET_VERSION has a sensible default. Test a built wheel against the oldest NumPy you claim to support (for example pip install numpy==1.23.5), not only against the one you built with.

C-API changes that break older code

The NumPy 2.0 migration guide lists the changes that matter for extension code:

  • PyArray_Descr is opaque. Replace direct field access such as descr->elsize with PyArray_ITEMSIZE(arr), PyDataType_ELSIZE, PyDataType_ALIGNMENT, PyDataType_FIELDS, PyDataType_NAMES and similar accessors. Cython 3 handles this for you.

  • Custom user dtypes register through PyArray_DescrProto.

  • A few macros and functions (PyDataType_FLAGCHK, PyDataType_REFCHK, NPY_BEGIN_THREADS_DESCR, PyArray_GETITEM, PyArray_SETITEM) now require the NumPy API to be imported, so call PyArray_ImportNumPyAPI() where import_array() has not run.

  • NPY_MAXDIMS and NPY_MAXARGS grew to 64. Avoid the macros; use NPY_RAVEL_AXIS for "axis=None".

  • Complex types use native C99 types. Replace c.real and c.imag with npy_creal, npy_cimag, npy_csetreal and npy_csetimag.

  • The default integer is 64-bit on 64-bit Windows. In C and Cython, NPY_DEFAULT_INT resolves to the right type, and code that needs the C long must cast explicitly.

  • The npy_2_compat.h header (in numpy/_core/include/numpy/) can be vendored so one source tree compiles against both 1.x and 2.x.

Later releases added their own notes. NumPy 2.1 hid the API symbols by default, so linking errors about PyArray_API or PyArray_RUNTIME_VERSION are solved by including numpy/ndarrayobject.h first or defining NPY_API_SYMBOL_ATTRIBUTE, and it removed many shims from npy_3kcompat.h. NumPy 2.3 removed the deprecated C macros such as NPY_OWNDATA (use NPY_ARRAY_OWNDATA). NumPy 2.5 requires Cython 3.0 or newer for NumPy’s Cython headers, requires MSVC 19.35 or newer, adds PyDataType_* accessor macros and stable-ABI support for free-threaded Python (PEP 803). NumPy 2.4 notes that extension modules use multi-phase initialisation, so deleting numpy from sys.modules and importing it again now raises ImportError. The upcoming 2.6 line raises the minimum GCC to 10.3 and soft-deprecates the PyArray_malloc family of allocator helpers.

Cython

Cython compiles Python with optional C type declarations into a C extension, and it is the most common way to speed up a numerical loop that cannot be vectorised. The NumPy-specific tool is the typed memoryview: a declared type such as double[:, ::1] gives a 2-D array with C-contiguous rows that you index at C speed without going through Python objects. The manual describes memoryviews as shaped, strided views that know their own extent, and notes that declaring the layout (::1 for the contiguous axis) lets Cython skip stride arithmetic.

The module below sums the rows of a 2-D float64 array. It declares the argument as a read-only contiguous memoryview, so Cython rejects non-contiguous or wrongly typed inputs, and it returns a regular NumPy array.

# cython: language_level=3, boundscheck=False, wraparound=False
import numpy as np
cimport numpy as cnp

cnp.import_array()

def row_sums(const double[:, ::1] a):
    cdef Py_ssize_t i, j, n = a.shape[0], m = a.shape[1]
    out = np.empty(n, dtype=np.float64)
    cdef double[::1] o = out
    cdef double s
    for i in range(n):
        s = 0.0
        for j in range(m):
            s += a[i, j]
        o[i] = s
    return out

A setup.py compiles it:

from setuptools import Extension, setup
from Cython.Build import cythonize
import numpy as np

ext = Extension("rowsum", ["rowsum.pyx"],
                include_dirs=[np.get_include()],
                define_macros=[("NPY_NO_DEPRECATED_API", "NPY_1_7_API_VERSION")])
setup(ext_modules=cythonize(ext, language_level=3))
python setup.py build_ext --inplace
python -c "import numpy as np, rowsum; a = np.arange(12.).reshape(3, 4); print(rowsum.row_sums(a), a.sum(axis=1)); rowsum.row_sums(a.T)"

Output:

[ 6. 22. 38.] [ 6. 22. 38.]
ValueError: ndarray is not C-contiguous

The last line comes from the transposed argument, which is a Fortran-ordered view. Pass np.ascontiguousarray(a.T) or declare the memoryview as double[:, :] to accept any strides at a small cost. The two compile options in the first line of the file switch off bounds checking and negative-index handling, so an out-of-range index becomes undefined behaviour: leave them on until the code is correct.

Points to remember:

  • cimport numpy and cnp.import_array() are only needed when you use NumPy’s C-API or its C types. Memoryviews over buffers do not need them.

  • You cannot return a memoryview to Python. Create the NumPy array first and take a view of it, as out and o do above.

  • Use Cython 3 with NumPy 2. NumPy’s own Cython headers require Cython 3.0 or newer from NumPy 2.5.

  • Release the GIL with with nogil: around loops that touch only C data, to let a thread pool run them in parallel (see the threading page). Free-threaded builds additionally need the extension to declare that it is safe without the GIL.

ctypes and numpy.ctypeslib

ctypes calls functions in an existing shared library without writing any extension code. NumPy supports it through numpy.ctypeslib.ndpointer, which describes the array a function expects. When you set argtypes with ndpointer, ctypes checks each argument’s dtype, number of dimensions, shape and flags when the call is made. The manual’s warning is that the caller is otherwise responsible for passing correct types, shapes and flags, and wrong pointers can crash the interpreter.

The C side is one function:

#include <stddef.h>
void scale(const double *x, double *y, size_t n, double k) {
    for (size_t i = 0; i < n; ++i) y[i] = k * x[i];
}

Build it as a shared library with your compiler (gcc -O2 -shared -fPIC -o libscale.so scale.c on Linux, libscale.dylib on macOS, a DLL on Windows) and call it:

import ctypes
import numpy as np
from numpy.ctypeslib import ndpointer

lib = ctypes.CDLL("./libscale.dylib")   # use libscale.so on Linux
lib.scale.argtypes = [
    ndpointer(np.float64, flags="C_CONTIGUOUS"),
    ndpointer(np.float64, flags="C_CONTIGUOUS", ndim=1),
    ctypes.c_size_t,
    ctypes.c_double,
]
lib.scale.restype = None

x = np.arange(5, dtype=np.float64)
y = np.empty_like(x)
lib.scale(x, y, x.size, 2.5)
print(y)
try:
    lib.scale(x[::2], y, 3, 2.0)
except ctypes.ArgumentError as e:
    print("ArgumentError:", str(e)[:70])

Output:

[ 0.   2.5  5.   7.5 10. ]
ArgumentError: argument 1: TypeError: array must have flags ['C_CONTIGUOUS']

The strided slice x[::2] is rejected because it is not contiguous, which is exactly the protection ndpointer buys you. Wrap raw library calls in a small Python function that uses np.ascontiguousarray or np.require to coerce inputs, so callers cannot trigger the error. Remember that ndpointer checks the array but not the length: pass the right n yourself. ctypes needs shared libraries (not static ones), and it is weak for C++ because there is no stable ABI to call.

Other helpers in numpy.ctypeslib: as_array and as_ctypes convert between ctypes objects and arrays, and load_library finds a library by name. Since NumPy 2.5, as_ctypes accepts only ndarray arguments: convert a NumPy scalar with np.asarray first.

F2PY: Fortran to Python

F2PY (Fortran to Python interface generator) ships with NumPy as the numpy.f2py module and the f2py command. It wraps Fortran 77/90/95 subroutines, Fortran 90/95 module subroutines and data (including allocatable arrays), COMMON blocks and C functions into a Python extension module. If the f2py command is not on your PATH, which is common on Windows, or if several Python installations have NumPy, run it as python -m numpy.f2py; that form always uses the interpreter you named.

Building an extension in one command

The manual’s walk-through starts from a Fortran 77 routine that adds two arrays:

C
      SUBROUTINE ZADD(A,B,C,N)
C
      DOUBLE COMPLEX A(*)
      DOUBLE COMPLEX B(*)
      DOUBLE COMPLEX C(*)
      INTEGER N
      DO 20 J = 1, N
         C(J) = A(J)+B(J)
 20   CONTINUE
      END
python -m numpy.f2py -c -m add add.f

This needs a Fortran compiler and the build tools Meson and Ninja (installable with pip). It scans the source, generates the C wrapper, compiles everything with Meson and leaves add.<platform tag>.so (or the equivalent) in the current directory. The generated interface is a literal translation of the Fortran, so its docstring shows five parameters, and it does not know that n is the length of a: misuse can crash Python. That is why F2PY has two ways to refine the interface.

Improving the interface with a signature file

Generate a signature (.pyf) file from the default interface, edit it, and build from it:

python -m numpy.f2py -h add.pyf -m add add.f

Edit the zadd section to add intents and dependencies:

subroutine zadd(a,b,c,n) ! in :add:add.f
   double complex dimension(n) :: a
   double complex dimension(n) :: b
   double complex intent(out),dimension(n) :: c
   integer intent(hide),depend(a) :: n=len(a)
end subroutine zadd
  • intent(out) makes c a return value created by the wrapper, so the caller no longer allocates it.

  • intent(hide) removes n from the Python arguments, and depend(a) with n=len(a) derives it from a.

python -m numpy.f2py -c add.pyf add.f

After this, add.zadd([1, 2, 3], [4, 5, 6]) returns array([5.+0.j, 7.+0.j, 9.+0.j]), and inputs are converted to the right type automatically. The same effect can be written inside the Fortran source with CF2PY comment directives (CF2PY INTENT(OUT) :: C, CF2PY INTENT(HIDE) :: N, CF2PY DOUBLE COMPLEX :: A(N) and so on), which avoids maintaining a separate .pyf file.

The only: and skip: lists restrict which routines are wrapped. F2PY has no per-file lists: if you list functions in only:, no other function is taken from any file.

Common options

Option Meaning

-m <name>

Name of the extension module (default untitled). Ignored if a .pyf file is given.

-c

Compile: build the extension module from sources, objects, libraries or a .pyf file.

-h <file.pyf>

Write a signature file instead of building. stdout prints it.

--f77flags=, --f90flags=

Fortran compiler flags.

-l<lib>, -L<dir>, -I<dir>

Link a library, add a library search directory, add an include directory.

-D<macro>, -U<macro>

Define or undefine a macro. Some non-gcc compilers need -DPREPEND_FORTRAN, -DNO_APPEND_FORTRAN or -DUPPERCASE_FORTRAN.

--dep <name>

A Meson dependency, for example --dep lapack. Repeatable.

--build-dir <dir>

Keep the generated build files in a directory (default: a temporary one).

--f2cmap <file>

Fortran KIND to C type mappings.

--[no-]freethreading-compatible

Declare whether the generated module can run without the GIL. The default is --no-freethreading-compatible.

From numpy.distutils to Meson

numpy.distutils was deprecated for years and was removed in NumPy 2.5.0, so F2PY builds now go through Meson. The removal is the reason old tutorials that call from numpy.distutils.core import setup, Extension with Fortran sources, or run python setup.py build with config_fc, do not work on NumPy 2.5. The command-line forms above are the replacement for the common case. The manual’s migration page gives the equivalents:

# compiler choice through environment variables (FC, CC, CFLAGS, FFLAGS, LDFLAGS ...)
FC=gfortran python -m numpy.f2py -c fib.f90 -m fib

# external dependency, resolved by Meson (maps to dependency("lapack"))
python -m numpy.f2py -c fib.f90 -m fib --dep lapack

# link a local library
python -m numpy.f2py -c fib.f90 -m fib -lmylib -L/path/to/mylib

# keep the generated Meson project for customisation
python -m numpy.f2py -c fib.f90 -m fib --build-dir blah

The --backend option still exists but only meson is accepted. On Windows, environment variables are not always honoured, and the guide recommends Meson native files instead. The generated Meson project in the build directory can be committed and used as a subproject of a larger Meson build, and customised with Meson’s own options. A package that needs a full build system (editable installs, wheels) should use meson-python with a meson.build that calls F2PY, rather than shelling out to f2py -c.

Release notes worth knowing: NumPy 2.1 added --freethreading-compatible (you must check yourself that the wrapped Fortran is thread-safe), 2.2 fixed several F2PY problems, and 2.5 made allocatable module variables visible in dir() and made intent(inplace) work on a separate copy that only accepts inputs of the same dtype.kind. The unreleased 2.6 line recognises the ISO Fortran Environment kinds (int16, int32, int64, real32, real64) in F2PY.

Common mistakes

  • Building a wheel against NumPy 1.x and shipping it with a numpy>=1.23 run-time requirement: it breaks on NumPy 2. Build against NumPy 2.x.

  • Forgetting import_array() (or cnp.import_array() in Cython) and getting a segmentation fault on the first NumPy call.

  • Using descr->elsize and other direct PyArray_Descr fields, which no longer compile.

  • Leaking the reference returned by PyArray_FROM_OTF on error paths.

  • Releasing the GIL around code that touches Python objects.

  • Passing non-contiguous slices to code that assumes contiguous memory, and relying on ndpointer without also passing the correct length.

  • Following a pre-2.5 tutorial that uses numpy.distutils for F2PY.

  • Declaring an F2PY module free-threading-compatible without auditing the Fortran code.