Python调用C程序

Python调用C程序

C程序

mylib.c

1
2
3
4
5
#include <stdio.h>

int add(int a, int b) {
    return a + b;
}

编译这个 C 文件为共享库:

1
gcc -shared -o mylib.so mylib.c

cffi(性能好)

1
pip install cffi

cffi_c.py

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
import cffi

ffi = cffi.FFI()
# 定义C函数的接口
ffi.cdef("""
    int add(int a, int b);
""")
# 加载动态链接库
lib = ffi.dlopen("./mylib.so") # 这里假设动态库名为test.so,需要将其放在与Python脚本同一目录下

# 调用C函数
result = lib.add(2, 3)
print(result)

运行 Python 程序

1
2
3
python cffi_c.py

5

ctypes(Python标准库)

ctypes_c.py

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
import ctypes

# 加载库
mylib = ctypes.CDLL("./mylib.so")

# 定义参数类型和返回值类型
mylib.add.argtypes = (ctypes.c_int, ctypes.c_int)
mylib.add.restype = ctypes.c_int

# 调用 C 函数
result = mylib.add(3, 4)
print(f"3 + 4 = {result}")

运行 Python 程序

1
2
3
python ctypes_c.py

3 + 4 = 7
comments powered by Disqus