轻松调用 C 语言共享库的强大工具
ctypes 是 Python 标准库中的一个模块,用于调用动态链接库(如 Windows 的 .dll 或 Linux/macOS 的 .so 文件)中的 C 函数。它允许你在不编写任何 C 扩展代码的情况下,直接与 C 语言编写的库进行交互。
以下是一个简单的例子:调用系统 C 库中的 printf 函数(在 Linux/macOS 上):
import ctypes
# 加载 C 标准库(Linux/macOS)
libc = ctypes.CDLL("libc.so.6") # macOS 可能是 libSystem.dylib
# 调用 printf
libc.printf(b"Hello from C!\n")
在 Windows 上,可以这样调用系统 API:
import ctypes
user32 = ctypes.windll.user32
user32.MessageBoxW(0, "Hello from ctypes!", "Message", 0)
CDLL()、WinDLL() 或 PyDLL()argtypes 和 restype 属性c_int、c_char_p、POINTER() 等ctypes.Structure 定义 C 风格结构假设你有一个 C 文件 math_utils.c:
// math_utils.c
int add(int a, int b) {
return a + b;
}
编译为共享库(Linux):
gcc -shared -fPIC -o math_utils.so math_utils.c
然后在 Python 中调用:
import ctypes
lib = ctypes.CDLL("./math_utils.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
stdcall vs cdecl)b"...")或使用 c_wchar_p 处理宽字符.dll / .so / .dylib)