Your first C API extension module — Python 3.16.0a0 documentation

docs.python.org

Tin mới

Extending and Embedding the Python Interpreter

Using the C API: Assorted topics

Python Module Index

3.16.0a0 Documentation

recommended third party tools

This tutorial will take you through creating a simple Python extension module written in C or C++.

The Python Tutorial

This tutorial will take you through creating a simple Python extension module written in C or C++.

virtual environment

This tutorial will take you through creating a simple Python extension module written in C or C++.

module export hook

The exception you got when you tried to import the module told you that Python is looking for a “module export function”, also known as a module export hook. Let’s define one.

PySlot_STATIC_DATA

Rather than NULL, the export hook should return the information needed to create a module. Let’s start with the basics: the name and docstring.

Exposing a function¶

To expose the system() C function directly to Python, we’ll need to write a layer of glue code to convert arguments from Python objects to C values, and the C return value back to Python.

Exposing a function¶

To expose the system() C function directly to Python, we’ll need to write a layer of glue code to convert arguments from Python objects to C values, and the C return value back to Python.

Exposing a function¶

To expose the system() C function directly to Python, we’ll need to write a layer of glue code to convert arguments from Python objects to C values, and the C return value back to Python.

Method definitions¶

To expose the C function to Python, you will need to provide several pieces of information in a structure called PyMethodDef [4]:

Returning an integer¶

Now, let’s take a look at the return value. Instead of None, we’ll want spam.system to return a number – that is, a Python int object. Eventually this will be the exit code of a system command, but let’s start with a fix

Returning an integer¶

Now, let’s take a look at the return value. Instead of None, we’ll want spam.system to return a number – that is, a Python int object. Eventually this will be the exit code of a system command, but let’s start with a fix

Accepting a string¶

Our C function, spam_system(), takes two arguments. The first one, PyObject *self, will be set to the spam module object. This isn’t useful in our case, so we’ll ignore it.

PyUnicode_AsUTF8AndSize()

Our C function, spam_system(), takes two arguments. The first one, PyObject *self, will be set to the spam module object. This isn’t useful in our case, so we’ll ignore it.