This section provides a comprehensive guide to the Python Library C API, which is a set of C functions that allow C/C++ programmers to write Python modules and extension modules.

Overview

The Python Library C API is designed to be easy to use and understand. It provides a rich set of functions to interact with Python objects, manage memory, and perform other tasks.

Key Features

  • Object Creation and Manipulation: Create and manipulate Python objects such as integers, floats, strings, and dictionaries.
  • Memory Management: Allocate and deallocate memory efficiently.
  • Error Handling: Handle Python exceptions and errors gracefully.
  • Function Wrapping: Wrap C/C++ functions to be called from Python code.

Getting Started

Before you start using the Python Library C API, you need to have a basic understanding of Python and C programming.

For more information on getting started with Python development, visit our Python Developer Center.

Functions

Object Creation

Here are some of the key functions for creating Python objects:

  • PyObject* PyLong_FromLong(long v);
  • PyObject* PyFloat_FromDouble(double v);
  • PyObject* PyString_FromString(const char *v);

Memory Management

Memory management is crucial when working with the Python Library C API:

  • void* PyMem_Malloc(size_t size);
  • void PyMem_Free(void *p);

Error Handling

Error handling is essential for debugging and maintaining your code:

  • void PyErr_SetString(PyObject *type, const char *msg);
  • PyObject* PyErr_Occurred(void);

Example

Here's a simple example of how to use the Python Library C API to create a Python module:

#include <Python.h>

static PyObject* my_function(PyObject *self, PyObject *args) {
    // Your code here
    return PyLong_FromLong(42);
}

static PyMethodDef MyMethods[] = {
    {"my_function", my_function, METH_VARARGS, "A simple function."},
    {NULL, NULL, 0, NULL}  /* Sentinel */
};

static struct PyModuleDef mymodule = {
    PyModuleDef_HEAD_INIT,
    "mymodule",
    NULL,
    -1,
    MyMethods
};

PyMODINIT_FUNC PyInit_mymodule(void) {
    return PyModule_Create(&mymodule);
}

For more detailed examples and tutorials, check out our API Reference.

Conclusion

The Python Library C API provides a powerful way to extend Python with C/C++. By following the guide above, you can start creating your own Python modules and extension modules.