1.使用C扩展
CPython还为开发者实现了一个有趣的特性,使用Python可以轻松调用C代码
开发者有三种方法可以在自己的Python代码中来调用C编写的函数-ctypes,SWIG,Python/C API。每种方式也都有各自的利弊。
首先,我们要明确为什么要在Python中调用C?
常见原因如下: - 你要提升代码的运行速度,而且你知道C要比Python快50倍以上 - C语言中有很多传统类库,而且有些正是你想要的,但你又不想用Python去重写它们 - 想对从内存到文件接口这样的底层资源进行访问 - 不需要理由,就是想这样做
2.CTypes
Python中的ctypes模块可能是Python调用C方法中最简单的一种。ctypes模块提供了和C语言兼容的数据类型和函数来加载dll文件,因此在调用时不需对源文件做任何的修改。也正是如此奠定了这种方法的简单性。
示例如下
实现两数求和的C代码,保存为add.c
//sample C file to add 2 numbers - int and floats
#include
int add_int(int, int);float add_float(float, float);int add_int(int num1, intnum2){return num1 +num2;
}float add_float(float num1, floatnum2){return num1 +num2;
}
接下来将C文件编译为.so文件(windows下为DLL)。下面操作会生成adder.so文件
#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
现在在你的Python代码中来调用它
from ctypes import *
#load the shared object file
adder = CDLL('./adder.so')#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_floatprint "Sum of 5.5 and 4.1 =", str(add_float(a, b))
输出如下
Sum of 4 and 5 = 9
Sum of 5.5 and 4.1 = 9.60000038147
在这个例子中