How to call a C language program in Python?
Python can call C language programs using the ctypes module. Here is a simple example:
Assume there is a C language program named hello.c with the following contents:
#include <stdio.h>
void say_hello() {
printf("Hello from C!\n");
}
Next, compile this C program into a shared library (a .so file in Linux, a .dll file in Windows) using the following command:
gcc -shared -o hello.so -fPIC hello.c
Next, call this shared library in Python, the code is as follows:
import ctypes
# 加载共享库
lib = ctypes.CDLL('./hello.so')
# 调用C语言函数
lib.say_hello()
When you run this Python code, it will output “Hello from C!” This successfully calls a C program through Python.