1. Using the C API#

This documentation provides a step-by-step guide for extending Caterpillar using its C API. The example provided demonstrates how to create a C extension module named _example integrated into the example library. This guide covers the setup of the build system using CMake and the implementation of the C extension module.

Before proceeding, ensure you have the following tools installed:

  • CMake

  • Python (with development headers)

  • Obviously caterpillar

Assuming you are using scikit-build to write your extension, the following project structure applies:

example-extension
├── CMakeLists.txt
├── pyproject.toml
└── src
    ├── example/
    │   └── /* put python sources here */
    └── _example.c

The CMakeLists.txt file configures the build system for the C extension module. Here’s the content of an example configuration:

 1cmake_minimum_required(VERSION 3.15...3.26)
 2project(${SKBUILD_PROJECT_NAME} LANGUAGES C)
 3
 4# Setup Python Development Module
 5find_package(
 6    Python
 7    COMPONENTS Interpreter Development.Module
 8    REQUIRED)
 9
10# Either setup the include directory manually or use caterpillar directly
11set(CP_INCLUDE_DIR "...")
12# or
13execute_process(
14    COMMAND "${Python_EXECUTABLE}" -m caterpillar --include-dir
15    OUTPUT_STRIP_TRAILING_WHITESPACE OUTPUT_VARIABLE CP_INCLUDE_DIR
16)
17
18# Setup the C extension module
19python_add_library(
20    _example       # module name
21    MODULE
22
23    src/_example.c # source files
24
25    WITH_SOABI
26)
27
28# setup include directories
29target_include_directories(
30    _example
31    PRIVATE
32    ${CP_INCLUDE_DIR}
33)
34
35# install extension
36install(
37    TARGETS _example
38    DESTINATION example # use '.' to install directly without parent package
39)

The src/_example.c file contains the implementation of the C extension module. To define a custom CAtom, please refer to work in progress. There will be only one important line when creating the custom module:

#include "caterpillar/caterpillar.h"

PyMODINIT_FUNC
PyInit__example(void) {
    PyObject *m;

    import_caterpillar(); // import and setup API

    /* create and setup module */
    // ...
    return m;
}

Install the created extension module using scikit-build:

pip install -v .

Hint

The c_extension directory contains an example extension written in C.