Fundamentals 4 min read

How to Call C/C++ Code from Python Using ctypes

This article explains how to improve Python performance by embedding C or C++ code: write the source, compile it into a shared library, and invoke its functions from Python with the ctypes module, providing step‑by‑step commands and example code for both C functions and C++ classes.

Python Programming Learning Circle
Python Programming Learning Circle
Python Programming Learning Circle
How to Call C/C++ Code from Python Using ctypes

When Python performance becomes a bottleneck, you can embed C/C++ code by compiling it into a shared library and loading it with the ctypes module.

The process consists of three steps: write the C/C++ implementation, compile it as a dynamic library, and invoke the library functions from Python.

Calling a C function – compile called_c.c with gcc -o libpycall.so -shared -fPIC called_c.c to produce libpycall.so , then load it in Python and call foo :

<code>import ctypes
dll = ctypes.cdll.LoadLibrary
lib = dll('./libpycall.so')
lib.foo(1, 3)
</code>

The program prints a:1, b:3 .

Calling a C++ class – wrap the class methods in an extern "C" block, compile with g++ -o libpycallcpp.so -shared -fPIC cpp_called.cpp , and use ctypes to call the exported functions:

<code>import ctypes
dll = ctypes.cdll.LoadLibrary
lib = dll('./libpycallcpp.so')
lib.display()
lib.display_int(0)
</code>

The output is:

<code>First display
Second display:0
</code>

This tutorial demonstrates the basic workflow; more advanced usage can be added later.

PythonCTutorialinteropc++dynamic libraryctypes
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.