python--ctypes模块调用C语言
开发环境
win10 系统
py:anaconda +PyCharm
C:gcc
win10 中GCC的安装:下载GCC的包,然后将相关文件添加到全局变量中就可以使用。
c代码
Python中的ctypes模块可能是Python调用C方法中最简单的一种。ctypes模块提供了和C语言兼容的数据类型和函数来加载dll文件,因此在调用时不需对源文件做任何的修改。也正是如此奠定了这种方法的简单性。
示例如下
实现两数求和的C代码,保存为add.c
//sample C file to add 2 numbers - int and floats
#include <stdio.h>
int add_int(int, int);
float add_float(float, float);
int add_int(int num1, int num2){
return num1 + num2;
}
float add_float(float num1, float num2){
return num1 + num2;
使用GCC编译
接下来将C文件编译为.so文件(windows下为DLL)。下面操作会生成adder.so文件
生成SO文件或者DLL文件对python的影响不大,所以无需特别注意
#For Linux
gcc -shared -Wl,-soname,adder -o adder.so -fPIC add.c
#For Mac
gcc -shared -Wl,-install_name,adder.so -o adder.so -fPIC add.c
#For windows
gcc -shared -Wl,-soname,adder -o adder.dll -fPIC add.c
现在在你的Python3代码中来调用它
from ctypes import *
# load the shared object file
adder = CDLL('./adder.dll')
# Find sum of integers
res_int = adder.add_int(4, 5)
print("Sum of 4 and 5 = " + str(res_int))
# Find sum of floats
a = c_float(5.5)
b = c_float(4.1)
add_float = adder.add_float
add_float.restype = c_float
print("Sum of 5.5 and 4.1 = ", str(add_float(a, b)))