当前位置:首页 > Python > 正文

Python ctypes详解(手把手教你用Python调用C语言函数)

在Python开发中,有时我们需要调用C语言编写的高性能函数或使用系统底层API。这时候,Python ctypes 模块就派上用场了!ctypes 是 Python 标准库的一部分,它允许你调用动态链接库中的 C 函数,而无需编写任何额外的绑定代码。

本教程将从零开始,带你了解如何使用 ctypes外部函数库 实现 Python与C语言交互,即使你是编程小白也能轻松上手!

什么是 ctypes?

ctypes 是 Python 的一个外部函数库(Foreign Function Interface, FFI),它可以加载共享库(如 Windows 的 .dll、Linux/macOS 的 .so/.dylib),并调用其中的 C 函数。通过 ctypes,你可以:

  • 调用 C 标准库函数(如 printfmalloc
  • 加载自己编写的 C 动态库
  • 传递和接收各种数据类型(整数、字符串、结构体等)
Python ctypes详解(手把手教你用Python调用C语言函数) ctypes  Python调用C函数 ctypes外部函数库 Python与C语言交互 第1张

第一步:加载系统动态库

我们先从最简单的例子开始——调用 C 标准库中的 printf 函数。

import ctypes# 在 Windows 上使用 msvcrt,在 Linux/macOS 上使用 libctry:    # 尝试加载 C 标准库    libc = ctypes.CDLL("libc.so.6")      # Linuxexcept OSError:    try:        libc = ctypes.CDLL("libc.dylib") # macOS    except OSError:        libc = ctypes.CDLL("msvcrt.dll") # Windows# 调用 printf 函数libc.printf(b"Hello from C!\n")

注意:字符串必须是字节串(bytes),所以要用 b"..." 前缀。

第二步:创建自己的 C 动态库

现在我们来编写一个简单的 C 函数,并编译成动态库供 Python 调用。

1. 创建 C 文件(math_utils.c):

// math_utils.c#include <stdio.h>int add(int a, int b) {    return a + b;}void greet(const char* name) {    printf("Hello, %s!\n", name);}

2. 编译为动态库:

  • Linux: gcc -shared -fPIC -o libmath_utils.so math_utils.c
  • macOS: gcc -shared -fPIC -o libmath_utils.dylib math_utils.c
  • Windows (MinGW): gcc -shared -o math_utils.dll math_utils.c

第三步:在 Python 中调用自定义 C 函数

import ctypesimport os# 获取当前脚本所在目录current_dir = os.path.dirname(os.path.abspath(__file__))# 加载动态库(根据操作系统选择文件名)if os.name == 'nt':  # Windows    lib_path = os.path.join(current_dir, "math_utils.dll")else:  # Linux/macOS    lib_name = "libmath_utils.so" if os.uname().sysname == "Linux" else "libmath_utils.dylib"    lib_path = os.path.join(current_dir, lib_name)lib = ctypes.CDLL(lib_path)# 调用 add 函数result = lib.add(5, 3)print(f"5 + 3 = {result}")  # 输出:5 + 3 = 8# 调用 greet 函数(需要指定参数类型)lib.greet.argtypes = [ctypes.c_char_p]lib.greet.restype = Nonelib.greet(b"Alice")  # 输出:Hello, Alice!

关键点说明:

  • argtypes:指定函数参数类型,避免传参错误
  • restype:指定返回值类型,默认是 c_int
  • 字符串必须转为 bytes 类型(使用 .encode()b"..."

常见数据类型映射

C 类型 ctypes 类型 Python 类型
int ctypes.c_int int
char* ctypes.c_char_p bytes
float ctypes.c_float float
double ctypes.c_double float

总结

通过本教程,你已经掌握了如何使用 Python ctypes 外部函数库来实现 Python与C语言交互。无论是调用系统库还是自定义动态库,ctypes 都提供了一种简洁高效的方式。

记住关键点:

  • 使用 CDLL 加载动态库
  • 设置 argtypesrestype 提高安全性
  • 字符串需转换为 bytes 类型

现在,你可以尝试将性能敏感的代码用 C 实现,再通过 ctypes外部函数库 在 Python 中调用,兼顾开发效率与运行速度!

关键词回顾:Python ctypesPython调用C函数ctypes外部函数库Python与C语言交互