Note: Do not use tutorials that are old or for Python 2
Python.h
and other header fileslibpython
librarypython3-config
In Debian:
apt install python3-dev build-essential
The above installs python3.x-dev
, plus libpython3-dev
and libpython3.x-dev
module.c
template¶#define PY_SSIZE_T_CLEAN
#include <Python.h>
static char module_doc[] = "This is a C extension\n\n"
"A very simple extension.";
# Wrapper functions go here!
static PyMethodDef methods[] = {
{NULL, NULL, 0, NULL}
};
static struct PyModuleDef moduledef = {
PyModuleDef_HEAD_INIT,
"module",
module_doc,
-1,
methods
};
PyMODINIT_FUNC
PyInit_module(void)
{
return PyModule_Create(&moduledef);
}
Based on: 1.1. A simple example, under Creating extensions without third party tools
system_wrap
¶static PyObject *
system_wrap(PyObject *self, PyObject *args)
{
const char *command;
int status;
if (!PyArg_ParseTuple(args, "s", &command))
return NULL;
status = system(command);
if (status < 0) {
return NULL;
}
return PyLong_FromLong(status);
}
static PyMethodDef methods[] = {
{"system", system_wrap, METH_VARARGS,
"Execute a shell command.\n\nReturns the exit code."},
{NULL, NULL, 0, NULL}
};
! ls -lt module.*
! gcc -c $(python3-config --cflags) module.c -o module.o
! gcc -shared $(python3.9-config --ldflags) module.o -o module.so
! ls -lt module.*
import module
help(module)
module.system('ls')
module.system('date')
module.system('foo')
Reference: Python Packaging User Guide
[build-system]
requires = ["setuptools", "wheel"]
build-backend = "setuptools.build_meta"
[metadata]
name = module
version = 0.1
author = John Smith
author_email = john@example.com
description = A minimal C extension
long_description = file: README.md
long_description_content_type = text/markdown
classifiers =
Programming Language :: Python :: 3
License :: OSI Approved :: LicenseName
Operating System :: OS Independent
from setuptools import setup, Extension
module = Extension('module',
sources = ['module.c'])
setup(ext_modules = [module])
! ~/envs/jupyter/bin/python -m build --no-isolation
! ls -lt dist
Name | Description |
---|---|
Pyrex | Pyhon-like language |
SWIG | Simplified Wrapper and Interface Generator |
Cython | Compile Python to C language extension modules |
Numba | Use LLVM for speed |
Boost.Python | |
PyBind11 | |
ctypes | In the Python standard library, does not require compilation |
cffi | C Foreign Function Interface, no C++ |