Backend Development 12 min read

Mixed Programming with Python and C/C++: Principles, Methods, and Performance Analysis

This article explains how to combine Python with C/C++ using ctypes, Python.h wrappers, and SWIG, provides step‑by‑step code examples, and analyzes performance through bubble‑sort experiments, demonstrating the trade‑offs and best practices for high‑performance mixed‑language development.

Python Programming Learning Circle
Python Programming Learning Circle
Python Programming Learning Circle
Mixed Programming with Python and C/C++: Principles, Methods, and Performance Analysis

Although language popularity rankings such as TIOBE only reflect current trends, many projects require mixing high‑level and low‑level languages to balance ease of use and performance.

The essence of Python‑C/C++ mixed programming is that Python code calls functions compiled into a shared library; data types must be converted between Python objects and native C types. CPython is the standard implementation, but alternatives like Jython, IronPython, and PyPy also exist.

Method 1 – Using ctypes : Write a simple C function, compile it to a shared object, and load it from Python.

extern "C" int addBuf(char* data, int num, char* outData);

int addBuf(char* data, int num, char* outData) { for (int i = 0; i < num; ++i) { outData[i] = data[i] + 3; } return num; }

Compile with:

gcc -pthread -fno-strict-aliasing -g -O2 -DNDEBUG -fwrapv -O3 -Wall -Wstrict-prototypes -fPIC addbuf.c -o libaddbuf.so

Python side:

from ctypes import * lib = cdll.LoadLibrary('libaddbuf.so') callAddBuf = lib.addBuf num = 4 numbytes = c_int(num) data_in = (c_byte * num)() for i in range(num): data_in[i] = i data_out = (c_byte * num)() ret = lib.addBuf(data_in, numbytes, data_out)

Method 2 – Writing a C extension with Python.h : Define module functions that receive PyObject* arguments, parse them, perform the native computation, and return a Python object.

#include <Python.h> static PyObject* spam_system(PyObject* self, PyObject* args) { const char* command; int sts; if (!PyArg_ParseTuple(args, "s", &command)) return NULL; sts = system(command); if (sts < 0) { PyErr_SetString(PyExc_RuntimeError, "System command failed"); return NULL; } return PyLong_FromLong(sts); } static PyMethodDef SpamMethods[] = { {"system", spam_system, METH_VARARGS, "Execute a shell command."}, {NULL, NULL, 0, NULL} }; PyMODINIT_FUNC initspam(void) { PyObject* m = Py_InitModule("spam", SpamMethods); if (m == NULL) return; PyObject* SpamError = PyErr_NewException("spam.error", NULL, NULL); Py_INCREF(SpamError); PyModule_AddObject(m, "error", SpamError); }

Build with a setup.py script using distutils and import the module in Python:

import spam spam.system("ls")

Method 3 – Using SWIG: Write an interface file ( spam.i ) that includes the C header and declares the functions to be wrapped.

%module spam %{ #include "spam.h" %} %include "spam.h" int system(const char* command);

Generate wrapper code and compile:

swig -c++ -python spam.i

SWIG produces spam_wrap.cxx and spam.py , which can be built into a Python extension module.

Performance Analysis: Four experiments compare pure Python, pure C, and the three mixed‑programming approaches using a bubble‑sort algorithm on a fixed‑size array (100 elements, 10 000 repetitions). Results show pure C runs in ~0.29 s, pure Python in ~10.3 s, ctypes‑based extension ~2.3 s, Python‑C‑API extension ~1.0 s, and SWIG‑wrapped code ~0.7 s, indicating that well‑designed C extensions can approach native C performance with only a small overhead.

Conclusion: Python lists are inefficient for CPU‑intensive loops; using C arrays via ctypes or writing C extensions is recommended for high‑performance sections. Mixed programming allows developers to keep Python’s productivity while delegating heavy computation to compiled code.

PerformancePythoncMixed ProgrammingctypesSWIG
Python Programming Learning Circle
Written by

Python Programming Learning Circle

A global community of Chinese Python developers offering technical articles, columns, original video tutorials, and problem sets. Topics include web full‑stack development, web scraping, data analysis, natural language processing, image processing, machine learning, automated testing, DevOps automation, and big data.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.