Calling C/C++ Code from Python Using ctypes and Shared Libraries
This tutorial explains how to call C and C++ code from Python by compiling source files into shared libraries, using the ctypes module to load and invoke functions, and demonstrates both simple C functions and C++ class methods with complete code examples and compilation instructions.
When Python code runs slowly, integrating C or C++ can improve performance. The process consists of three steps: write the C/C++ implementation, compile it into a shared library, and call the library from Python.
1. Python calling a C function
The C source called_c.c defines a simple function foo . Compile it with:
<code>//编译命令 gcc -o libpycall.so -shared -fPIC called_c.c
#include <stdio.h>
int foo(int a, int b){
printf("a:%d, b:%d.", a, b);
return 0;
}
</code>Then load and invoke it in Python:
<code>import ctypes
dll = ctypes.cdll.LoadLibrary
lib = dll('./libpycall.so')
lib.foo(1, 3)
</code>Running the script prints a:1, b:3 .
2. Python calling a C++ class
Because C++ name mangling hides symbols, the functions must be exported with extern "C" . The C++ source cpp_called.cpp defines a class TestLib with overloaded display methods and wraps them in an extern block.
<code>//Python调用c++(类)动态链接库
#include <iostream>
using namespace std;
class TestLib {
public:
void display();
void display(int a);
};
void TestLib::display() {
cout << "First display" << endl;
}
void TestLib::display(int a) {
cout << "Second display:" << a << endl;
}
extern "C" {
TestLib obj;
void display() { obj.display(); }
void display_int(int a) { obj.display(a); }
}
</code>Compile the shared library:
<code>g++ -o libpycallcpp.so -shared -fPIC cpp_called.cpp</code>Load and use it from Python:
<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>Both examples show how to bridge Python with native code, providing a foundation for more advanced integrations.
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.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.