轻松实现 Python 与 C 语言的高效交互
ctypes 是 Python 标准库中的一个模块,用于调用 C 兼容的共享库(如 Windows 的 .dll 或 Linux/macOS 的 .so 文件)。它允许你在不编写任何 C 扩展代码的情况下,直接从 Python 调用 C 函数。
这在需要高性能计算、访问操作系统底层功能或复用现有 C 库时非常有用。
libmath.so 或 math.dll)。ctypes.CDLL() 或 ctypes.WinDLL() 加载该库。argtypes)和返回类型(restype)。假设我们有一个 C 函数 add(int a, int b),编译为 libmath.so(Linux)或 math.dll(Windows):
// math.c
#include <stdio.h>
int add(int a, int b) {
return a + b;
}
// 编译命令(Linux): gcc -shared -fPIC -o libmath.so math.c
// 编译命令(Windows): gcc -shared -o math.dll math.c
Python 调用代码如下:
# python_ctypes_example.py
import ctypes
import os
# 加载动态库(路径根据系统调整)
if os.name == 'nt': # Windows
lib = ctypes.CDLL('./math.dll')
else: # Linux/macOS
lib = ctypes.CDLL('./libmath.so')
# 设置函数签名
lib.add.argtypes = (ctypes.c_int, ctypes.c_int)
lib.add.restype = ctypes.c_int
# 调用函数
result = lib.add(3, 5)
print("3 + 5 =", result) # 输出: 3 + 5 = 8
ctypes 提供了多种 C 类型的 Python 映射:
ctypes.c_int → intctypes.c_char_p → 字符串(bytes)ctypes.c_double → 浮点数ctypes.POINTER(ctypes.c_int) → 指针ctypes.Structure 定义bytes(如 b"hello")或显式编码;返回字符串需设置 restype = ctypes.c_char_p。
argtypes 和 restype,否则可能导致崩溃或错误结果。.dll vs .so vs .dylib)。cffi 或 Cython 替代。