The Python C API provides a set of functions that allow C programs to interact with Python objects. This guide provides an overview of the C API and includes links to more detailed documentation.

Overview

The Python C API is a set of functions that expose the Python object model to C programs. This allows C programs to create and manage Python objects, call Python functions, and access Python variables.

Key Features

  • Object Creation: Create new Python objects of various types, such as integers, floats, and dictionaries.
  • Function Calls: Call Python functions from C, passing arguments and retrieving return values.
  • Variable Access: Access Python variables and modify their values.
  • Error Handling: Handle errors that occur during C API calls.

Getting Started

Before using the Python C API, you need to ensure that Python is properly installed on your system and that you have access to the Python headers and libraries.

Installation

  1. Install Python on your system.
  2. Find the location of the Python headers and libraries.
  3. Configure your C compiler to include the Python headers and link against the Python libraries.

For detailed instructions on installation, refer to the Python installation guide.

Examples

Here are some simple examples to get you started:

Create a Python Integer

#include <Python.h>

int main() {
    Py_Initialize();

    // Create a new Python integer
    PyObject* integer = PyLong_FromLong(42);

    // Check if the integer was created successfully
    if (!integer) {
        PyErr_Print();
        return 1;
    }

    // Print the integer
    printf("Integer: %ld\n", PyLong_AsLong(integer));

    // Clean up
    Py_DECREF(integer);
    Py_Finalize();

    return 0;
}

Call a Python Function

#include <Python.h>

int main() {
    Py_Initialize();

    // Import the 'math' module
    PyObject* math_module = PyImport_ImportModule("math");
    if (!math_module) {
        PyErr_Print();
        Py_Finalize();
        return 1;
    }

    // Get the 'sin' function from the 'math' module
    PyObject* sin_function = PyObject_GetAttrString(math_module, "sin");

    // Check if the function was retrieved successfully
    if (!sin_function || !PyCallable_Check(sin_function)) {
        PyErr_Print();
        Py_DECREF(math_module);
        Py_Finalize();
        return 1;
    }

    // Call the 'sin' function with a single argument
    PyObject* args = PyTuple_Pack(1, PyFloat_FromDouble(3.14159));
    PyObject* result = PyObject_CallObject(sin_function, args);

    // Check if the call was successful
    if (!result) {
        PyErr_Print();
    } else {
        printf("sin(3.14159) = %f\n", PyFloat_AsDouble(result));
    }

    // Clean up
    Py_DECREF(args);
    Py_DECREF(result);
    Py_DECREF(sin_function);
    Py_DECREF(math_module);
    Py_Finalize();

    return 0;
}

For more information on the Python C API, check out the Python C API documentation.

Back to Developer Center